如何处理 json 异常以防止应用程序崩溃?

diw*_*iwa 1 java android

我正在开发一个 android 应用程序,它显示来自返回 json 的 URL 的图像。但是每当 json 返回空值时,我的应用程序都会崩溃并关闭。我也尝试过一些处理 null 的方法,但不确定它是否正确。这是我的代码

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

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Create a progressdialog
        mProgressDialog = new ProgressDialog(GridActivity.this);
        // Set progressdialog title
        mProgressDialog.setTitle("Fetching Images");
        // Set progressdialog message
        mProgressDialog.setMessage("Loading...");
        mProgressDialog.setIndeterminate(false);
        // Show progressdialog
        mProgressDialog.show();
    }

    @Override
    protected Void doInBackground(Void... params) {
        // Create an array
        arraylist = new ArrayList<HashMap<String, String>>();
        // Retrieve JSON Objects from the given URL address
        jsonobject = JSONfunctions
                .getJSONfromURL("http://url.com");
        try {
            // Locate the array name in JSON
            jsonarray = jsonobject.getJSONArray("wallpaper");
            if(jsonobject==null) {
                Toast.makeText(GridActivity.this, "error" , Toast.LENGTH_SHORT).show();
            } else{


                for (int i = 0; i < jsonarray.length(); i++) {
                    HashMap<String, String> map = new HashMap<String, String>();
                    jsonobject = jsonarray.getJSONObject(i);
                    // Retrive JSON Objects
                    //  map.put("rank", jsonobject.getString("rank"));
                    map.put("category", jsonobject.getString("category"));
                    //   map.put("population", jsonobject.getString("population"));
                    map.put("image", jsonobject.getString("image"));
                    // Set the JSON Objects into the array
                    arraylist.add(map);
                }
            }
        } catch (JSONException e) {
            Toast.makeText(GridActivity.this,"Error on the response", 3000).show();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void args) {


        gridview =(GridView)findViewById(R.id.gridViewCustom);
        // Pass the results into ListViewAdapter.java
        adapter = new GridViewAdapter(GridActivity.this, arraylist);


        button = (Button) findViewById(R.id.button);

        // add button listener
        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                //Log.v("obj", "Creating view..." + jsonobject);
               // Log.v("arry", "Creating view..." + jsonarray);
                new loadMoreListView().execute();
            }
        });
        // Set the adapter to the ListView
        gridview.setAdapter(adapter);
        // Close the progressdialog
        mProgressDialog.dismiss();

    }
}
Run Code Online (Sandbox Code Playgroud)

日志猫:

07-02 17:38:07.069 11429-11461/com.fbphoto_comments.app E/log_tag?解析数据 org.json.JSONException 时出错:无法将 org.json.JSONObject$1 类型的值 null 转换为 JSONObject

Lit*_*ild 5

任何Exception都可以通过使用try-catch块来处理。

try{
  // code that may throw exception
}catch(org.json.JSONException exception){
  // how you handle the exception
  // e.printStackTrace();
}  
Run Code Online (Sandbox Code Playgroud)

更新:
您正在迭代 aJSONArray并查看相同的文档,它说:

密集索引的值序列。值可以是 JSONObjects、其他 JSONArrays、Strings、Booleans、Integers、Longs、Doubles、null 或 NULL 的任意组合。

这意味着JSONObject.NULL数组中可能存在值。这就是你的错误状态。尝试添加一个if-else来检查你得到了什么。

更多信息:http : //developer.android.com/reference/org/json/JSONObject.html#NULL