Java 如何处理 json 异常以防止应用程序崩溃?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24530866/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to handle json Exception to prevent app crash?
提问by diwa
I am developing a android app which shows the images from URL which returns a json. But my app keeps getting crashed and closed whenever the json returns null value. I also tried something to handle null but am not sure if its right way. Here is my code
我正在开发一个 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();
}
}
Logcat:
日志猫:
07-02 17:38:07.069 11429-11461/com.fbphoto_comments.app E/log_tag﹕ Error parsing data org.json.JSONException: Value null of type org.json.JSONObject$1 cannot be converted to JSONObject
07-02 17:38:07.069 11429-11461/com.fbphoto_comments.app E/log_tag﹕错误解析数据 org.json.JSONException: 类型 org.json.JSONObject$1 的值 null 无法转换为 JSONObject
回答by Laurent
You should move your JSONfunctions.getJSONfromURL("http://url.com") in the try-catch block.
您应该在 try-catch 块中移动 JSONfunctions.getJSONfromURL(" http://url.com")。
回答by Little Child
Any Exception
can be handled by using try-catch
blocks.
任何Exception
都可以通过使用try-catch
块来处理。
try{
// code that may throw exception
}catch(org.json.JSONException exception){
// how you handle the exception
// e.printStackTrace();
}
Update:
You are iterating over a JSONArray
and going over the documentation for the same, it says:
更新:
您正在迭代 aJSONArray
并查看相同的文档,它说:
A dense indexed sequence of values. Values may be any mix of JSONObjects, other JSONArrays, Strings, Booleans, Integers, Longs, Doubles, null or NULL.
密集索引的值序列。值可以是 JSONObjects、其他 JSONArrays、Strings、Booleans、Integers、Longs、Doubles、null 或 NULL 的任意组合。
Which means that JSONObject.NULL
values may be present in the array. That is what your error states. Try adding an if-else
to check what you get.
这意味着JSONObject.NULL
数组中可能存在值。这就是你的错误状态。尝试添加一个if-else
来检查你得到了什么。
More here: http://developer.android.com/reference/org/json/JSONObject.html#NULL
更多信息:http: //developer.android.com/reference/org/json/JSONObject.html#NULL
回答by TBI
JSONException Class will handle the Json Exception put your JSONfunctions.getJSONfromURL("http://url.com")in Try block and this will work from app crashing.
JSONException 类将处理 Json 异常,将您的 JSONfunctions.getJSONfromURL(" http://url.com") 在 Try 块中,这将在应用程序崩溃时起作用。
Try to parse the Json as getting Response from Server Whether it is JsonObject or JsonArray in response. Try to make the response from the server in same format in case of error as well.
尝试将 Json 解析为从服务器获取响应无论是 JsonObject 还是 JsonArray 作为响应。如果出现错误,请尝试以相同的格式从服务器进行响应。
回答by Basem S H Saabneh
you are calling Toast inside doInBackground() , delete toast message. You can not call Toast inside doInBackground
您在 doInBackground() 中调用 Toast ,删除 toast 消息。你不能在 doInBackground 中调用 Toast