Dynamically inserting string into a string array in Android

Viewed 63372

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?

3 Answers

String Array in Java has a defined size that should be given while declaration, you cannot change it later by adding or removing elements and the pure concept of the dynamic array does not exit in java. Read detailed article here...

This is the right way to declare an array of fixed size.

        String[] myString = new String[5];
        fruits[0]="hello";
        fruits[1]="hello";
        fruits[2]="hello";
        fruits[3]="hello";
        fruits[4]="hello";

Instead, you can use a List to perform a similar task. The list is purely dynamic and you can add multiple values on runtime. This is the right way to declare a list in Android using JAVA.

   ArrayList<String> fruits = new ArrayList<String>();
        fruits.add("Value 1");
        fruits.add("Value 2");
        fruits.add("Value 3");
        fruits.add("Value 4");
        fruits.add("Value 5");
        fruits.add("Value 6");
        fruits.add("Value 7");
// add as much values as per requirement
// you can also use loops to add multiple values

Related