org.json Android系统错误。JSONException:在字符0处输入结束

时间:2022-10-29 14:29:01

I'm developing a test Android application that must display some data from a Mysql db and sent some back. But I don't know what is wrong with my code.

我正在开发一个测试Android应用程序,它必须显示一些来自Mysql db的数据并将一些数据发回。但是我不知道我的代码有什么问题。

Here's my Activity.

这是我的活动。

private Spinner spinner;
// add items into spinner dynamically
@SuppressWarnings("unused")
public void addListenerOnSpinnerItemSelection() {
    spinner = (Spinner) findViewById(R.id.spinner);

    try {

        JSONArray data = new JSONArray(getHttpPost(url,params));
        final List<String> MyArrList = new ArrayList<String>();   
        if (data != null)
        {

        for (int i = 0; i < data.length(); i++) {
            JSONObject c = (JSONObject) data.get(i);
            strLevel = c.getString("lv_name");
            MyArrList.add(strLevel);
            Log.i("Value", strLevel);

        }

        ArrayAdapter<String> vehicleAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, MyArrList);
        vehicleAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(vehicleAdapter);
        }
        else
        {
            Log.i("Value","Null value");
        }

        final AlertDialog.Builder ad = new AlertDialog.Builder(this);           
        spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

        public void onItemSelected(AdapterView<?> arg0, View selectedItemView,
                    int position, long id) {
            params.add(new BasicNameValuePair("level", strLevel));

            try{
            strLevel = (spinner.getSelectedItem().toString());

            String resultServer  = getHttpPost(url,params);
            Log.i("Send to Server", strLevel);
            Log.i("Result", resultServer);
            }
            catch (Exception e)
            {
                Log.e("ERROR", e.toString());
            }

            } 

            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub
                Toast.makeText(SettingActivity.this,
                        "Your Selected : Nothing",
                            Toast.LENGTH_SHORT).show(); 
            }


        }); 

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
  }

Here's My PHP file. Sent data

这是我的PHP文件。发送数据

<?php
ob_start();
$objConnect = mysql_connect("mydbms","xxxx","xxxx");
$objDB = mysql_select_db("xxxx");

$level = $_POST["level"];
setcookie("level", $level, time()+60*60*24*3650);
$strSQL = "SELECT question.id_lv, level_detail.lv_name FROM question LEFT JOIN level_detail ON question.id_lv = level_detail.id_lv GROUP BY id_lv ASC"; 

$objQuery = mysql_query($strSQL) or die(mysql_error());
$intNumField = mysql_num_fields($objQuery);
$resultArray = array();
while($obResult = mysql_fetch_array($objQuery))
{
    $arrCol = array();
    for($i=0;$i<$intNumField;$i++)
    {
        $arrCol[mysql_field_name($objQuery,$i)] = $obResult[$i];
    }
    array_push($resultArray,$arrCol);
}
mysql_close($objConnect);

echo json_encode($resultArray);
ob_end_flush();
?>

Here's PHP file. Used data.

这是PHP文件。使用数据。

<?php
ob_start();
$objConnect = mysql_connect("mydbms","xxxx","xxxx");
$objDB = mysql_select_db("xxxx");

$strQuestionID = $_POST["sQuestion"];
$strSQL = "SELECT question.id_question, question.q_name, question.q_means, question.picture_path, level_detail.lv_name FROM question";
$strSQL .= " LEFT JOIN level_detail ON question.id_lv = level_detail.id_lv";
$strSQL .= " WHERE question.id_lv =  '".$_COOKIE['level']."'";
$strSQL .= " AND q_type =  'Dragdrop'";
$strSQL .= " ORDER BY RAND( ) LIMIT 1"; 

$objQuery = mysql_query($strSQL) or die(mysql_error());
$objResult = mysql_fetch_array($objQuery) or die(mysql_error());
    if($objResult)
    {
        $arr["QID"] = $objResult["id_question"];
        $arr["question"] = $objResult["q_name"];
        $arr["means"] = $objResult["q_means"];
        $arr["picture"] = $objResult["picture_path"];
    }

mysql_close($objConnect);

echo json_encode($arr);
ob_end_flush();
?>

Here's HttpPost.

这是HttpPost。

public String getHttpPost(String url,List<NameValuePair> params) {
    StringBuilder str = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);

    try {
        httpPost.setEntity(new UrlEncodedFormEntity(params));
        HttpResponse response = client.execute(httpPost);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200) { // Status OK
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {
                str.append(line);
            }
        } else {
            Log.e("Log", "Failed to download result..");
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return str.toString();
}

Here's LogCat.

这是LogCat。

03-16 11:29:02.108: W/System.err(2016):     org.json.JSONException: End of input at character 0 of 
03-16 11:29:02.112: W/System.err(2016):     at org.json.JSONTokener.syntaxError(JSONTokener.java:450)
03-16 11:29:02.116: W/System.err(2016):     at org.json.JSONTokener.nextValue(JSONTokener.java:97)
03-16 11:29:02.116: W/System.err(2016):     at org.json.JSONObject.<init>(JSONObject.java:154)
03-16 11:29:02.116: W/System.err(2016):     at org.json.JSONObject.<init>(JSONObject.java:171)
03-16 11:29:02.116: W/System.err(2016):     at com.example.dfromcode.MainActivity.onCreate(MainActivity.java:136)
03-16 11:29:02.116: W/System.err(2016):     at android.app.Activity.performCreate(Activity.java:5104)
03-16 11:29:02.116: W/System.err(2016):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
03-16 11:29:02.116: W/System.err(2016):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
03-16 11:29:02.116: W/System.err(2016):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
03-16 11:29:02.120: W/System.err(2016):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-16 11:29:02.120: W/System.err(2016):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
03-16 11:29:02.120: W/System.err(2016):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-16 11:29:02.120: W/System.err(2016):     at android.os.Looper.loop(Looper.java:137)
03-16 11:29:02.120: W/System.err(2016):     at android.app.ActivityThread.main(ActivityThread.java:5041)
03-16 11:29:02.124: W/System.err(2016):     at java.lang.reflect.Method.invokeNative(Native Method)
03-16 11:29:02.124: W/System.err(2016):     at java.lang.reflect.Method.invoke(Method.java:511)
03-16 11:29:02.132: W/System.err(2016):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-16 11:29:02.132: W/System.err(2016):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-16 11:29:02.132: W/System.err(2016):     at dalvik.system.NativeStart.main(Native Method)

1 个解决方案

#1


1  

The exception message:

异常信息:

  org.json.JSONException: End of input at character 0

suggests to me that your code is trying to parse an empty String. In other words your getHttpPost method (which you haven't shown us!) is failing.

提示我您的代码正在解析一个空字符串。换句话说,您的getHttpPost方法(您还没有向我们展示它!)正在失败。

(By bet is that getHttpPost is not correctly handling the case where the server is giving an error response.)

(我敢打赌getHttpPost没有正确处理服务器给出错误响应的情况。)


I suspect that this test is part of the problem:

我怀疑这个测试是问题的一部分:

    JSONArray data = new JSONArray(getHttpPost(url,params));
    ... 
    if (data != null)

It is actually impossible for data to be null. The new operation is either going to give you a (non-null!) reference to a new object, or it is going to terminate with an exception.

数据实际上不可能为空。新的操作将为您提供一个(非空!)对新对象的引用,或者它将以异常结束。

#1


1  

The exception message:

异常信息:

  org.json.JSONException: End of input at character 0

suggests to me that your code is trying to parse an empty String. In other words your getHttpPost method (which you haven't shown us!) is failing.

提示我您的代码正在解析一个空字符串。换句话说,您的getHttpPost方法(您还没有向我们展示它!)正在失败。

(By bet is that getHttpPost is not correctly handling the case where the server is giving an error response.)

(我敢打赌getHttpPost没有正确处理服务器给出错误响应的情况。)


I suspect that this test is part of the problem:

我怀疑这个测试是问题的一部分:

    JSONArray data = new JSONArray(getHttpPost(url,params));
    ... 
    if (data != null)

It is actually impossible for data to be null. The new operation is either going to give you a (non-null!) reference to a new object, or it is going to terminate with an exception.

数据实际上不可能为空。新的操作将为您提供一个(非空!)对新对象的引用,或者它将以异常结束。