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
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