Home » Android » dynamic – Dynamically inserting string into a string array in Android

dynamic – Dynamically inserting string into a string array in Android

Posted by: admin June 15, 2020 Leave a comment

Questions:

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?

How to&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()]);

Answer:

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");
       }

Answer:

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