如何解决在JSON解析中获取空指针异常?

时间:2014-06-06 14:23:39

标签: java json android-asynctask

我正在开发一个从json解析中检索数据的应用程序。我在执行异步任务时遇到空指针异常。

请给我任何建议。

Asynch班级在这里

    private class GetContacts extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(ContactListActivity.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        // Creating service handler class instance
        JSONParser sh = new JSONParser();

        // Making a request to url and getting response
        JSONObject jsonStr = sh.getJSONFromUrl(url);

        Log.d("Response: ", "> " + jsonStr);

        if (jsonStr != null) {
            try {

                // Getting JSON Array node
                contacts = jsonStr.getJSONArray(TAG_CONTACTS);

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

                    String name = c.getString(TAG_NAME);
                    String mobile = c.getString(TAG_PHONE_MOBILE);
                    ContactBean bean=new ContactBean();
                    bean.setName(name);
                    bean.setPhoneNo(mobile);
                    contactList.add(bean);

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();
        /**
         * Updating parsed JSON data into ListView
         * */
        ContanctAdapter adapter = new ContanctAdapter(
                ContactListActivity.this, R.layout.alluser_row, contactList);

        lv.setAdapter(adapter);
    }

从此方法获取json数据

 public JSONObject getJSONFromUrl(String url) {
    // Making HTTP request
    try {
      // defaultHttpClient
      DefaultHttpClient httpClient = new DefaultHttpClient();
      HttpPost httpPost = new HttpPost(url);
      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();
      json = sb.toString();
    } catch (Exception e) {
      Log.e("Buffer Error", "Error converting result " + e.toString());
    }
    // try parse the string to a JSON object
    try {
      jObj = new JSONObject(json);
    } catch (JSONException e) {
      Log.e("JSON Parser", "Error parsing data " + e.toString());
    }
    // return JSON String
    return jObj;
  }

1 个答案:

答案 0 :(得分:0)

这可能有很多语句可能导致NullPointer。正如评论所表明的那样,如果没有痕迹就难以识别。然而,最可能的地方是

// Getting JSON Array node
contacts = jsonStr.getJSONArray(TAG_CONTACTS);

// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
    ...
}

可能没有TAG-CONTACTS json数组,并且contacts对象可能为null ..并且在循环内部,您试图获取长度。如果对象为null,则for循环可能导致NPE。