JimmyHo
JimmyHo

Reputation: 289

JSON Object can't getstring

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

Upvotes: 1

Views: 436

Answers (2)

SagaciousLearner
SagaciousLearner

Reputation: 88

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.

Upvotes: 1

Elye
Elye

Reputation: 60081

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

Upvotes: 2

Related Questions