0

Why am I getting this error and how can I fix it? I have 43 items in my ListView, where is index 4338 coming from?

I looked at the solution here : JSONArray Exception : Index 50 out of range [0..50). Is there any limit on JsonArray and modified my code accordingly but still getting the errors.

These errors come up in logcat - my ListView loads eventually, after about 20 seconds which seems way too long - but only after this error displays in Logcat after repeating hundreds of times - index 3829 all the way up to 4338 (skipping a few along the way).

Here's my code :

public class PopulistoListView extends AppCompatActivity {

    // this is the php file name where to select from.
    // we will post the user's phone number into Php and get the matching user_id
    private static final String SelectUserReviews_URL = "http://www.example.com/SelectUserReviews.php";

    //we are posting phoneNoofUser, the key is phonenumberofuser, which we see in php
    public static final String KEY_PHONENUMBER_USER = "phonenumberofuser";

    private ProgressDialog pDialog;
    private List<Review> reviewList = new ArrayList<Review>();
    private ListView listView;
    private CustomPopulistoListAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listview_contacts);

        listView = (ListView) findViewById(R.id.list);
        adapter = new CustomPopulistoListAdapter(this, reviewList);
        listView.setAdapter(adapter);

        //get the phone number value from shared preferences file instead
        //of from the VerifiedUserPhoneNumber class because we might not
        //be coming from that class, for example on Edit, New etc. The phone
        //number needs to be posted for this listview to load properly.

        SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
        final String phoneNoofUser = sharedPreferences.getString("phonenumberofuser", "");

        pDialog = new ProgressDialog(this);
        // Showing progress dialog before making http request
        pDialog.setMessage("Loading...");
        pDialog.show();

        //post the phone number of the logged in user to SelectUserReviews.php and from that
        //get the logged in user's reviews
        StringRequest stringRequest = new StringRequest(Request.Method.POST, SelectUserReviews_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        //hide the 'loading' box when the page loads
                        hidePDialog();
                        //toast the response of SelectUserReviews.php, which has been converted to a
                        //JSON array in the Php file with JSON encode
                        Toast.makeText(PopulistoListView.this, response, Toast.LENGTH_LONG).show();

                        //break up the JSON Array into parts
                        //we need to sort out this error we keep getting in logcat
                        final int numberOfItemsInResp = response.length();
                        for (int i = 0; i < numberOfItemsInResp; i++) {
                            try {
                                JSONArray responseObject = new JSONArray(response);
                                JSONObject obj = responseObject.getJSONObject(i);
                                Review review = new Review();
                                review.setCategory(obj.getString("category"));
                                review.setName(obj.getString("name"));
                                review.setPhone(obj.getString("phone"));
                                review.setComment(obj.getString("comment"));
                                //we are getting the review id so we can pull extra needed info, like Address etc
                                review.setReviewid(obj.getString("reviewid"));
                                // Toast.makeText(PopulistoListView.this, responseObject.toString(), Toast.LENGTH_LONG).show();

                                reviewList.add(review);

                            } catch (JSONException e) {
                                Log.e("MYAPP", "unexpected JSON exception", e);
                                // Do something to recover ... or kill the app.
                            }
                        }
                        // notifying list adapter about data changes
                        // so that it renders the list view with updated data
                        adapter.notifyDataSetChanged();

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(PopulistoListView.this, error.toString(), Toast.LENGTH_LONG).show();

                    }

                }) {
            @Override
            //post info to php
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                //phoneNoofUser is the value we get from Android, the user's phonenumber.
                //the key is "phonenumberofuser". When we see "phonenumberofuser" in our php,
                //put in phoneNoofUser
                params.put(KEY_PHONENUMBER_USER, phoneNoofUser);
                return params;

            }

        };
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        hidePDialog();
    }

    private void hidePDialog() {
        if (pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }
    }

    }

In logcat I get the error several times :

unexpected JSON exception
org.json.JSONException: Index 4001 out of range [0..43)
at org.json.JSONArray.get(JSONArray.java:282)
at org.json.JSONArray.getJSONObject(JSONArray.java:510)
at PopulistoListView$1.onResponse(PopulistoListView.java:96)
at PopulistoListView$1.onResponse(PopulistoListView.java:81)

Line 96 is :

JSONObject obj = responseObject.getJSONObject(i);

Line 81 is :

        new Response.Listener<String>() {

Thanks for any help.

CHarris
  • 2,693
  • 8
  • 45
  • 71

2 Answers2

6

Your for loop is iterating over this range: (int i = 0; i < numberOfItemsInResp; i++), but numberOfItemsInResp is the length of a String object.

Without getting too deep into it (really just based off of the other code you've written), I think you'd be better off with this:

JSONArray responseObject = new JSONArray(response);

for (int i = 0; i < responseObject.length(); i++) {
    JSONObject obj = responseObject.getJSONObject(i);
    ...
}
Ben P.
  • 52,661
  • 6
  • 95
  • 123
  • Looks good, but do you know how I can stop these org.json.JSONException errors coming up in red ? https://www.screencast.com/t/3QUJrxyc – CHarris Jul 22 '17 at 00:52
  • 1
    Add try catch to that block of code, to catch the JSONException, like this, **try { ///Your code } catch (JSONException e) { e.printStackTrace(); }** – Muthukrishnan Rajendran Jul 22 '17 at 01:04
  • 1
    Try to use optJSONObject(i) insead of getJSONObject(i), I explained [here](https://stackoverflow.com/a/45204800/900128) – Muthukrishnan Rajendran Jul 22 '17 at 01:08
  • 1
    @CHarris `org.json.JSONException` isn't exactly an error, it's just that your code doesn't handle that type of exception. Methods like `new JSONArray(response)` and `responseObject.getJSONObject()` can throw this exception if the string isn't valid json. Imagine you call `new JSONArray("hello world")`... that will fail. So you must add a `catch (JSONException e)` block and handle these exceptions. – Ben P. Jul 22 '17 at 03:47
1

The cause of error in line 81 is that your phoneNoofuser is incorrect, you have to modify it.

final String phoneNoofUser = sharedPreferences.getString("KEY_PHONENUMBER_USER", "");