Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically inserting string into a string array in Android

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?

like image 899
Stefan Doychev Avatar asked Aug 04 '11 08:08

Stefan Doychev


2 Answers

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()]);
like image 195
Sherif elKhatib Avatar answered Nov 01 '22 11:11

Sherif elKhatib


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");
       }
like image 20
Rasel Avatar answered Nov 01 '22 13:11

Rasel