ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

php – 如何解决org.json.JSONException中的错误?

2019-07-24 17:37:03  阅读:303  来源: 互联网

标签:android php json android-studio jsonexception


我正在创建一个可以通过将ID号放在editText中来检索单词的应用程序.我继续得到这个错误.如何解决这个问题呢? org.json.JSONException:{“server_response”:“Bird”}没有值

enter image description here

这是我的主Activity.java

package com.example.keam.lastnato;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class MainActivity extends Activity {

String id;
String word;
InputStream is=null;
String result=null;
String line=null;
String data ="";
TextView disp;
String url = "http://192.168.0.10/checkpls.php";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final EditText e_id=(EditText) findViewById(R.id.editText1);
    Button select=(Button) findViewById(R.id.button1);
    disp = (TextView)findViewById(R.id.textView);
    select.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            id = e_id.getText().toString();
            select();
        }
    });
}

public void select()
{
    class readThis extends AsyncTask<String, Void, String> {
        protected String doInBackground(String... params){

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

            nameValuePairs.add(new BasicNameValuePair("id",id));

            try
            {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(params[0]);
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
                Log.e("pass 1", "connection success ");
            }
            catch(Exception e)
            {
                Log.e("Fail 1", e.toString());
           Toast.makeText(getApplicationContext(), "Invalid IP Address",
                        Toast.LENGTH_LONG).show();
            }

            try
            {
                BufferedReader reader = new BufferedReader
                        (new InputStreamReader(is,"iso-8859-1"),8);

                StringBuilder sb = new StringBuilder();
                while ((line = reader.readLine()) != null)
                {
                    sb.append(line);
                }
                is.close();
                result = sb.toString();
                Log.e("pass 2", "connection success ");
            }
            catch(Exception e)
            {
                Log.e("Fail 2", e.toString());
            }

            try
            {

                JSONObject json_data = new JSONObject(result);
                word = json_data.getString(result);
                Toast.makeText(getBaseContext(), "Name: " + word, 
                Toast.LENGTH_SHORT).show();

            }

            catch(JSONException e)
            {
                Log.e("Fail 3", e.toString());
                Log.e("log_tag", "Failed data was: " + result);
            }
            return word;
        }
    }

    readThis hello = new readThis();
    hello.execute(new String[] {url});
}
}

这是我的activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.keam.lastnato.MainActivity">

<EditText
    android:id="@+id/editText1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="39dp"
    android:padding="11dp"
    android:hint="Id"
    android:ems="10"
    android:inputType="number">

    <requestFocus />
</EditText>

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/editText1"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="24dp"
    android:onClick="parseJSON"
    android:padding="11dp"
    android:text="Select" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Text"
    android:id="@+id/textView"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true" />
 </RelativeLayout>

这是我的PHP文件“checkpls.php”

 <?php
$con = mysqli_connect("localhost", "root", "1234", "check") or die ("Error ".mysqli_error($con));
$id = $_POST['id'];
$sql = "SELECT * FROM tblcheckword where id like '$id';";
$result = mysqli_query($con, $sql) or die("Error in selecting ".mysqli_error($con));

$response = array();
if(mysqli_num_rows($result) > 0){
    while($row = mysqli_fetch_array($result))
    {
        array_push($response, array("id"=>$row[0],"word"=>$row[1],"meaning"=>$row[2]));
        $retrieve = $row[1];
    }
    echo json_encode(array("server_response" => $retrieve));
}else{
    echo "Retrieve failed";
}

mysqli_close($con);


?>

这是我在WAMP phpmyadmin中的tblcheckword

数据库名称=“检查”

enter image description here

这是我的logcat错误.

08-19 14:10:48.367 23305-23536/com.example.keam.lastnato E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
                                                                       Process: com.example.keam.lastnato, PID: 23305
                                                                       java.lang.RuntimeException: An error occured while executing doInBackground()
                                                                           at android.os.AsyncTask$3.done(AsyncTask.java:300)
                                                                           at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
                                                                           at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
                                                                           at java.util.concurrent.FutureTask.run(FutureTask.java:242)
                                                                           at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
                                                                           at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
                                                                           at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
                                                                           at java.lang.Thread.run(Thread.java:841)
                                                                        Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
                                                                           at android.os.Handler.<init>(Handler.java:200)
                                                                           at android.os.Handler.<init>(Handler.java:114)
                                                                           at android.widget.Toast$TN.<init>(Toast.java:372)
                                                                           at android.widget.Toast.<init>(Toast.java:105)
                                                                           at android.widget.Toast.makeText(Toast.java:264)
                                                                           at com.example.keam.lastnato.MainActivity$1readThis.doInBackground(MainActivity.java:120)
                                                                           at com.example.keam.lastnato.MainActivity$1readThis.doInBackground(MainActivity.java:61)
                                                                           at android.os.AsyncTask$2.call(AsyncTask.java:288)
                                                                           at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                           at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
                                                                           at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
                                                                           at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
                                                                           at java.lang.Thread.run(Thread.java:841) 
   08-19 14:10:49.969 23305-23536/com.example.keam.lastnato I/Process: Sending signal. PID: 23305 SIG: 9

解决方法:

更改word = json_data.getString(result); to word = json_data.getString(“server_response”);

更新:

public void select(){
    readThis hello = new readThis();
    hello.execute(new String[] {url});
}

private class ReadThis extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

            nameValuePairs.add(new BasicNameValuePair("id",id));

            try
            {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(params[0]);
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
                Log.e("pass 1", "connection success ");
            }
            catch(Exception e)
            {
                Log.e("Fail 1", e.toString());
           Toast.makeText(getApplicationContext(), "Invalid IP Address",
                        Toast.LENGTH_LONG).show();
            }

            try
            {
                BufferedReader reader = new BufferedReader
                        (new InputStreamReader(is,"iso-8859-1"),8);

                StringBuilder sb = new StringBuilder();
                while ((line = reader.readLine()) != null)
                {
                    sb.append(line);
                }
                is.close();
                result = sb.toString();
                Log.e("pass 2", "connection success ");
            }
            catch(Exception e)
            {
                Log.e("Fail 2", e.toString());
            }
            }
            return result ;
        }

        @Override
        protected void onPostExecute(String result) {
            try
        {

            JSONObject json_data = new JSONObject(result);
            word =  json_data.getString("server_response");
            Toast.makeText(getBaseContext(), "Name: " + word, 
            Toast.LENGTH_SHORT).show();

        }

        catch(JSONException e)
        {
            Log.e("Fail 3", e.toString());
            Log.e("log_tag", "Failed data was: " + result);
        }
        }

        @Override
        protected void onPreExecute() {}

        @Override
        protected void onProgressUpdate(Void... values) {}
    }

标签:android,php,json,android-studio,jsonexception
来源: https://codeday.me/bug/20190724/1524590.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有