1

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

diwa
  • 169
  • 2
  • 2
  • 11

4 Answers4

5

Any Exception can be handled by using try-catch blocks.

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:

A dense indexed sequence of values. Values may be any mix of JSONObjects, other JSONArrays, Strings, Booleans, Integers, Longs, Doubles, null or 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.

More here: http://developer.android.com/reference/org/json/JSONObject.html#NULL

An SO User
  • 24,612
  • 35
  • 133
  • 221
1

You should move your JSONfunctions.getJSONfromURL("http://url.com") in the try-catch block.

Laurent
  • 31
  • 4
  • Given the minimal error information provided, this looks like the most likely solution. – Stephen C Jul 02 '14 at 12:28
  • @user3652550 You look to use the jsonobject afterwards (new loadMoreListView().execute();), before using it, check if it is not null and include the JSON loader in the try-catch block as described. – Laurent Jul 02 '14 at 12:40
  • cf. http://stackoverflow.com/questions/10965528/android-validating-json-when-getting-a-response-from-a-server-to-avoid-a-jsone – Laurent Jul 02 '14 at 12:51
  • @user3652550 - What did you do, and how did it "not work"? The fix provided should prevent you getting that exception in the logcat. That's what you wanted ... isn't it? – Stephen C Jul 02 '14 at 22:52
0

JSONException Class will handle the Json Exception put your JSONfunctions.getJSONfromURL("http://url.com")in Try block and this will work from app crashing.

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.

TBI
  • 2,789
  • 1
  • 17
  • 21
  • I think the second paragraph is bad advice. The JSON should be parsed as one or the other, depending on that the application can cope with. Only attempt to parse it "either way" if the application can genuinely cope with both forms. There is no point in accepting lots of different forms unless they mean something different. – Stephen C Jul 02 '14 at 12:32
0

you are calling Toast inside doInBackground() , delete toast message. You can not call Toast inside doInBackground