0

我正在学习 android 中的 JSON 解析。我的 logcat 显示 NullPointerException onpostexecute 方法。我已经分享了下面的代码。

    protected String doInBackground(String... urls) 
{

    // TODO Auto-generated method stub
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url1);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();           

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        result = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

   return result;

}
 protected void onPostExecute(String result) {
      // try parse the string to a JSON object
        try {
            jObj = new JSONObject(result);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

    }
      public JSONObject getJSONFromUrl()
    { 
  return jObj;
     }

Main Activity 中的 JSONParser 对象

JSONParser jParser = (JSONParser) new JSONParser().execute(url);
    try
    {
        Thread.sleep(2000);

    }
    catch (InterruptedException e)
    {
        // TODO: handle exception
        e.printStackTrace();
    }

    // getting JSON string from URL
    JSONObject json = jParser.getJSONFromUrl();

我无法弄清楚问题所在。提供建议……

4

1 回答 1

0

从服务器获得响应后,您始终必须添加 Null 检查。

于 2013-01-04T07:26:30.750 回答