Android JSON null对象引用错误

时间:2015-04-25 17:06:10

标签: android json android-asynctask stackexchange-api

我在我的应用程序中使用StackExchange API,它返回如下响应:

{  
   "items":[  
      {  
         "tags":[  
            "android",
            "gridview",
            "android-fragments",
            "android-activity"
         ],
         "owner":{  
            "reputation":30,
            "user_id":3303863,
            "user_type":"registered",
            "profile_image":"http://i.stack.imgur.com/44pCy.jpg?s=128&g=1",
            "display_name":"chris.b",
            "link":"http://stackoverflow.com/users/3303863/chris-b"
         },
         "is_answered":false,
         "view_count":7,
         "answer_count":0,
         "score":0,
         "last_activity_date":1429979620,
         "creation_date":1429979620,
         "question_id":29867827,
         "link":"http://stackoverflow.com/questions/29867827/android-app-close-without-error-on-click-of-the-first-gridview-item",
         "title":"Android App Close without Error, on click of the first gridview Item"
      },
      {  
         "tags":[  
            "android",
            "genymotion"
         ],
         "owner":{  
            "reputation":61,
            "user_id":213199,
            "user_type":"registered",
            "accept_rate":54,
            "profile_image":"https://www.gravatar.com/avatar/2f0b0c0e0e449255b5e2892b10b97ba4?s=128&d=identicon&r=PG",
            "display_name":"Stella",
            "link":"http://stackoverflow.com/users/213199/stella"
         },
         "is_answered":false,
         "view_count":7,
         "answer_count":0,
         "score":0,
         "last_activity_date":1429979268,
         "creation_date":1429979268,
         "question_id":29867773,
         "link":"http://stackoverflow.com/questions/29867773/unable-to-run-android-app-in-genymotion-emulator",
         "title":"Unable to run Android app in Genymotion emulator"
      },

我正在使用以下代码从URL获取字符串:

public String readJSON() {
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url);

    HttpResponse response = null;
    try {
        response = client.execute(httpGet);
    } catch (IOException e) {
        e.printStackTrace();
    }
    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    if (statusCode == 200) {
        HttpEntity entity = response.getEntity();
        InputStream content = null;
        try {
            content = entity.getContent();
        } catch (IOException e) {
            e.printStackTrace();
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        //Log.e(re.class.toString(), "Failed to download file");
    }
    return builder.toString();
}

我正在使用异步任务在文本视图中显示问题,如下所示:

public class JSONTask extends AsyncTask<String,String,JSONObject>
{
    private ProgressDialog pDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Getting Data ...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected JSONObject doInBackground(String... params) {
        try {
            ob1 = new JSONObject(readJSON());
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ob1;
    }

    @Override
    protected void onPostExecute(JSONObject jsonObject) {
        try {
            mJSONArr = jsonObject.getJSONArray("items");
            for(int i=0;i<20;i++)
            {
                ob2 = mJSONArr.getJSONObject(i);
                holder+=ob2.getString("title");
            }
            tv.setText(holder);
            pDialog.dismiss();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

但是我收到错误的说法

  

“尝试调用虚方法'org.json.JSONObject   关于空对象引用的org.json.JSONArray.getJSONObject(int)'

在这些方面:

        mJSONArr = ob1.getJSONArray("items");

public class JSONTask extends AsyncTask<String,String,JSONObject>

我该如何解决这个问题?另外,如何在此JSON响应中从“所有者”对象访问“显示名称”?

谢谢

2 个答案:

答案 0 :(得分:0)

ob1

中没有onPostExecute()

更改

mJSONArr = ob1.getJSONArray("items");

mJSONArr = jsonObject.getJSONArray("items");

在对其执行任何操作之前,还要添加空检查

@Override
protected void onPostExecute(JSONObject jsonObject) {
    try {
        mJSONArr = jsonObject.getJSONArray("items");
        if(mJSONArr != null)
        {
            for(int i=0;i<20;i++)
            {
                ob2 = mJSONArr.getJSONObject(i);
                if(ob2 != null)
                {
                    holder+=ob2.getString("title");
                }
            }
        }
        if(holder != null && holder.length() > 0)
            tv.setText(holder);
        else
            tv.setText("Error in fetching Data");
        pDialog.dismiss();
    } catch (JSONException e) {
        e.printStackTrace();
        tv.setText("Error in fetching Data");
        pDialog.dismiss();
    }
}

答案 1 :(得分:0)

首先访问您必须访问json数组items的标题,然后在JsonObject MyJson =YourJsonArray.getJsonObject(i)之后访问其项目,然后使用您想要的标记示例String title=Myjson.getString("title")

这是您在代码中更改的内容

  @Override
    protected void onPostExecute(JSONObject jsonObject) {
  pDialog.dismiss();//hiding the progress dialog
        try {
           if(ob1!=null && !ob1.isNull("items")){ //avoiding exceptions
            mJSONArr = ob1.getJSONArray("items");

        for(int i=0;i<mJsonArr.length();i++)
        {
            ob2 = mJSONArr.getJSONObject(i);
            holder+=ob2.getString("title");
        }
        tv.setText(holder);
        pDialog.dismiss();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}}

编辑:您收到该错误是因为您使用“i&lt; 20”而不是“i&lt; jsonArray.length()”,如果json只有9个项目(0 ... 8),并且你试图获得第10个项目(i = 9),你将得到该错误,因为没有有效的jsonObject

Eit2:对于进度对话框,请在执行后执行

 pDialog.dismiss();

Edit3:使用此类JSONParser.java

    package YourPackage;

import android.app.Application;
import android.os.Debug;
import android.util.Log;
import android.widget.Toast;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

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

            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

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


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

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "UTF-8"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
            System.out.println(json);
        } 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;

    }
}

将其添加为全局变量

    JSONParser jsonParser = new JSONParser();

并在你的asyncTask中 使用这个

   List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("key",key));//if you have params
      ob1= jsonParser.makeHttpRequest(Your_url,
                    "POST" or "GET", params); //choose post method or get method 

取而代之的是

   ob1 = new JSONObject(readJSON());