RightOn
RightOn

Reputation: 11

NullPointerException with listview on android

I am want to show this json data in to listview. Iam having this problem:

java.lang.NullPointerException: Attempt to invoke virtual method 'org.json.JSONObject org.json.JSONArray.getJSONObject(int)' on a null object reference

private String[] arrow() throws JSONException {
        json = new JSONObject();
        JSONArray com= null;
        String[] list = new String[10];
        try {
            com = json.getJSONArray("parameters"); // this have 10 different values
        } catch (JSONException e) {
            e.printStackTrace();
        }
                for (int i = 0; i < 10; i++)
                    try {
                        json = com.getJSONObject(i);
                        String forward= json.getString("forward");
                        String back= json.getString("back");

                        list[i]="Forward: " + forward + "\n" + "Backward: " + back;
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
        return list;
    }

I did it with textview but cant do it with listview, i get this nullpointer.. Please help. Thanks.

Upvotes: 1

Views: 73

Answers (1)

Sharjeel
Sharjeel

Reputation: 15798

There are multiple problems. The first problem is that you are using two try/catch. If you get exception in first one, you still go to 2nd try and try to run code.

json = com.getJSONObject(i);

this line is in 2nd try catch. In your case it seems com is null because there was exception in 1st try/catch.

  try { 
            com = json.getJSONArray("parameters"); // this have 10 different values

            for (int i = 0; i < com.length(); i++) {
                json = com.getJSONObject(i);
                String forward= json.getString("forward");
                String back= json.getString("back");

               list[i]="Forward: " + forward + "\n" + "Backward: " + back;
            }
      } catch (JSONException e) {
          e.printStackTrace();
      } 

Upvotes: 1

Related Questions