1

I'm having some trouble with I want going to get a JSON format array-object string,

and the array definite [{"code":"123","path":"456"},.....}]

but when working on

JArray.getJSONObject(0).getString("code")

it's display "null"

Has anyone could explain why it happens?

thanks for your solutions

for(int i=0;i<JArray.length();i++) {
            try {
                avr_hash = JArray.getJSONObject(i).getString("code");
                img_adress[JArray.length()] = JArray.getJSONObject(i).getString("path");
            }catch (JSONException e){
                Log.e("Catch obj",e.toString());
            }
}

enter image description here

IDE : Android Studio

solution : array index setting erroneous

2
  • 3
    Shouldn't you use i instead of exist_json_array_count inside your loop? Commented Feb 19, 2016 at 2:44
  • You are right, but it's no different when 0 or next Commented Feb 19, 2016 at 2:49

2 Answers 2

2

I think you should replace the exist_json_array_count to i as below

   for(int i=0;i<exist_json_array_count;i++) {
        try {
            avr_hash = JArray.getJSONObject(i).getString("code");
            img_adress[i] = JArray.getJSONObject(i).getString("path");
        }catch (JSONException e){
            Log.e("Catch obj",e.toString());
        }

The reason is, the index shouldn't be the size of the array, as it starts from 0 to 13 (since the size is 14).

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks help, but the problem persists with getString
Perhaps you could post the new error message after changing the index?
I simplify exist_json_array_count -> JArray.length(), and correction index, it's restored the job, thanks very much!
1

For the error message it seems the array is being accessed by an index that does not exist.

int exist_json_array_count = JArray.length(); 

The above represents the length of an array. Arrays in Java have zero based indexing. So an array with length 4 will have elements at 0,1,2,3 indexes.

img_adress[exist_json_array_count] = JArray.getJSONObject(exist_json_array_count).getString("path");

In the above line "exist_json_array_count" variable has length of the array, which explains the fact the error message that the array is being accessed with an invalid index.

Clearly from the error message : [0..14) means range of valid indexes is including 0 and excluding 14.

  img_adress[i] = JArray.getJSONObject(i).getString("path");

Above code is a suggested change assuming you want all the paths to be in im_address array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.