I receive some data as a JSON response from a server. I extract the data I need and I want to put this data into a string array. I do not know the size of the data, so I cannot declare the array as static. I declare a dynamic string array:
String[] xCoords = {};
After this I insert the data in the array:
for (int i=0; i<jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
xCoords[i] = json_data.getString("xCoord");
}
But I receive the
java.lang.ArrayIndexOutOfBoundsException
Caused by: java.lang.ArrayIndexOutOfBoundsException
What is the way to dynamically insert strings into a string array?
Use ArrayList although it is not really needed but just learn it:
ArrayList<String> stringArrayList = new ArrayList<String>();
for (int i=0; i<jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
stringArrayList.add(json_data.getString("xCoord")); //add to arraylist
}
//if you want your array
String [] stringArray = stringArrayList.toArray(new String[stringArrayList.size()]);
Try like this
String stringArray[];
stringArray=new String[jArray.length()];
String xCoords[]=new String[jArray.length()];;
for (int i=0; i<jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
xCoords[i] = json_data.getString("xCoord");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With