在Android中将字符串动态插入字符串数组中

时间:2021-06-29 13:17:09

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:

我从服务器收到一些数据作为JSON响应。我提取了我需要的数据,我想将这些数据放入字符串数组中。我不知道数据的大小,所以我不能将数组声明为静态。我声明了一个动态字符串数组:

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?

将字符串动态插入字符串数组的方法是什么?

2 个解决方案

#1


38  

Use ArrayList although it is not really needed but just learn it:

使用ArrayList虽然不是真的需要但只是学习它:

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

#2


6  

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

#1


38  

Use ArrayList although it is not really needed but just learn it:

使用ArrayList虽然不是真的需要但只是学习它:

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

#2


6  

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