【问题标题】:My Error parsing data org.json.JSONException: End of input at character 0 of我的错误解析数据 org.json.JSONException:在字符 0 处输入结束
【发布时间】:2016-10-02 16:53:46
【问题描述】:

当我运行 php 脚本时它返回异常。 这是我的java类

public class ShowAllQuestions extends ListActivity {

    int cntChoice;
    ArrayList<String> selected;
    Button getChoice;
    // Progress Dialog
    private ProgressDialog pDialog;
    public static String mode;
    private static final String CONNECTION_FAILED_MSG = "connection";
    private ArrayList<String> nameList = new ArrayList<String>();
    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();
    String id;
    ArrayList personList;

    // url to get all products list
    private static String url_all_products = "http://www.rpscadda.com/QuizAPP/getallmcq.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_Person = "person";
    private static final String TAG_PID = "id";
    private static final String TAG_NAME = "fname";
    private static final String TAG_RESULT = "result";


    // products JSONArray
    JSONArray person = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.all_questions);

        personList = new ArrayList<HashMap<String, String>>();
        final ListView myList=(ListView)findViewById(android.R.id.list);
        getChoice=(Button) findViewById(R.id.button);
        getChoice.setOnClickListener(new Button.OnClickListener(){



            @Override

            public void onClick(View v) {

                // TODO Auto-generated method stub



               selected=new ArrayList<String>();;



                cntChoice = myList.getCount();

                SparseBooleanArray sparseBooleanArray = myList.getCheckedItemPositions();

                for(int i = 0; i < cntChoice; i++){

                    if(sparseBooleanArray.get(i)) {

                        selected.add(i, myList.getItemAtPosition(i).toString()) ;

                         Log.d("Message",String.valueOf(selected.get(i)));



                        String selectedFromList =selected.get(i);
                        String a[]=selectedFromList.split(" ");
                        Toast.makeText(getApplicationContext(), a[0], Toast.LENGTH_SHORT).show();
                        selected.add(i,a[0]);
                        Log.d("Message",a[0]);





                    }

                }
                try {
                    //receiving result from Connect class.
                    String result = new Connect().execute().get();
                    if (result != null) {
                    Log.i("Test", result);

                        JSONObject jsonObject = new JSONObject(result);
                        String response = (String) jsonObject.get("result");
                        if(response.equals("success")){
                            Toast.makeText(getApplicationContext(),"connected",Toast.LENGTH_LONG).show();
                        } else if(response.equals(CONNECTION_FAILED_MSG)) {
                            Toast.makeText(getApplicationContext(), "Couldn't connect to remote database.", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(getApplicationContext(), "Something went wrong", Toast.LENGTH_SHORT).show();
                        }

                    } else {
                        Log.i("Test", "Result is empty");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }



            }});

        try {
            //receiving result from Connect class.
            ArrayList<String> result = new LoadAllProducts().execute().get();
            if(result != null){
                Log.i("BulkQuestions", "Updating");


                ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                        android.R.layout.simple_list_item_multiple_choice, result);
                 myList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
                for(String r : result){
                    Log.i("BulkQuestions", r);
                }

                myList.setAdapter(adapter);
                myList.refreshDrawableState();

            }




        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }


    }

    public class Connect extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            BufferedReader inBuffer = null;
            String result = "fail";


            //sending POST request.
            try {
                String url="http://www.rpscadda.com/QuizAPP/deletemcq.php";
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost request = new HttpPost(url);
                for(int i=0;i<selected.size();i++) {
                    List<NameValuePair> postParameters = new ArrayList<NameValuePair>();

                    postParameters.add(new BasicNameValuePair("id", selected.get(i)));

                    UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
                            postParameters);

                    request.setEntity(formEntity);
                    //executing request and storing result.
                    HttpResponse httpResponse = httpClient.execute(request);

                    //translating into input stream
                    HttpEntity httpEntity = httpResponse.getEntity();
                    InputStream content = httpEntity.getContent();

                    //reading from the buffer.
                    BufferedReader reader = new BufferedReader(new InputStreamReader(content, "iso-8859-1"), 8);
                    StringBuilder sb = new StringBuilder();
                    String line = null;

                    //storing into string.
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                    result = sb.toString();
                }
            } catch(Exception e) {
                // Do something about exceptions
                result = e.getMessage();
                e.printStackTrace();
            } finally {
                if (inBuffer != null) {
                    try {
                        inBuffer.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return  result;    }

        @Override
        protected void onPostExecute(String result) {

        }
    }
    class LoadAllProducts extends AsyncTask<String, String, ArrayList<String>> {


        protected ArrayList<String> doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
            // Check your log cat for JSON reponse
            Log.d("All Products: ", json.toString());

            try {
                // Checking for SUCCESS TAG
                String result = json.getString(TAG_RESULT);

                if (result.equals("success")) {
                    // products found
                    // Getting Array of Products
                    person = json.getJSONArray("mcq");

                    // looping through All Products
                    for (int i = 0; i < person.length(); i++) {
                        JSONObject c = person.getJSONObject(i);

                        // Storing each json item in variable
                         id = c.getString("id");
                        String name = id +" "+c.getString("question");
                        nameList.add(name);
                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        map.put(TAG_PID, id);
                        map.put(TAG_NAME, name);

                        Log.i("BulkQuestions", name);

                        // adding HashList to ArrayList
                        personList.add(map);

                    }
                } else {                   Log.i("BulkQuestions", "result = failed");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return nameList;
        }

        @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
        protected void onPostExecute(String file_url) {
        }

    }
}

这是我的 php 代码

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);

    // Check connection
    if ($conn->connect_error) {
        $response['result']="connection";
        die("Connection failed: " . $conn->connect_error);
    } 


    $result = $conn->query("SELECT * FROM mcq");

    $num_rows = $result->num_rows;
    if($num_rows > 0){  
        // looping through all results
        // products node
        $response["mcq"] = array();

        while ($row = $result->fetch_assoc()) {
            // print_r($row);
            // temp user array
            $mcq= array();
            $mcq["id"] = $row["id"];
                    $mcq["question"] = utf8_decode($row["question"]);
            $mcq["op1"] = utf8_decode($row["op1"]);
            $mcq["op2"] = utf8_decode($row["op2"]);
            $mcq["op3"] = utf8_decode($row["op3"]);
            $mcq["op4"] = utf8_decode($row["op4"]);
            $mcq["correct"] = utf8_decode($row["correct"]);
            $mcq["explanation"] = utf8_decode($row["explanation"]);
            $mcq["maincat"] = $row["mainCategory"];
            $mcq["subcat"] = $row["subcategory"];



            $response["mcq"][] = $mcq;
        }
        $response['result']= "success";

    } else {
    //  echo "Error: " . $sql . "<br>" . $conn->error;
        $response['result']= "failed";
    }
    $conn->close();
     // echoing JSON response   
    echo json_encode($response);?>

我的 Logcat 错误 [LogcatError][1] [1]:http://i.stack.imgur.com/M7BSb.png

当我在表中/从表中插入/检索短字符串时,我的代码运行良好,而如果我插入长字符串,它运行良好,尽管它在检索时出现此异常。

我是一个 php 初学者,并在 stackoverflow 上发布了我的第一个问题,非常抱歉描述不佳。

【问题讨论】:

  • getAllMcq.php 在浏览器上加载时也会返回 null。

标签: java php android json


【解决方案1】:

从错误的描述来看,PHP 似乎返回了空的 JSON 数据。我相信你已经检查过表格,确保查询到的数据存在于表格中。

你能检查 PHP 日志文件吗?您可以从命令行在服务器上运行该 PHP 脚本(或其中的一部分),以便检查错误并查看返回的数据吗?

【讨论】:

  • 是的,数据存在表中。我已经通过在 chrome 浏览器上运行它来检查脚本,当我添加包含少量字符的英语/其他语言的数据时,它可以完美地工作,而我输入像“400 个其他语言字符”这样的大字符串时,它将数据存储在 utf8-编码字符串到表中,并在检索时返回 null。
  • 当它返回 null 时,你能在 php/webserver/appserver 日志文件中看到任何错误吗?
  • 看看这个post。它建议您在插入 MySQL 之前转义您的外来字符,以便以后可以由 json_encode() 正确处理它们。查看你在 MySql 中的数据,看看你是否有类似 u0644 而不是 \u0644 的东西
  • 您正在对从数据库返回的字符串运行 utf8_decode。 SO上的大多数帖子似乎都建议相反。运行 utf8_encode (如果尚未编码),然后在其上运行 json_encode 。看here。由于我们不知道您的数据在数据库中的格式,您可能需要尝试 (1) 通过删除 utf8_decode (2) 通过对从 MySql 返回的字符串使用 utf8_encode。
  • 让我检查一下。谢谢
猜你喜欢
  • 2014-06-03
  • 2013-08-20
  • 2014-07-11
  • 2017-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多