android - 将字符串动态插入到Android中的字符串数组中

标签 android dynamic arrays

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

String[] xCoords = {};

之后我将数据插入数组:

   for (int i=0; i<jArray.length(); i++) {
         JSONObject json_data = jArray.getJSONObject(i);
         xCoords[i] = json_data.getString("xCoord");
   }

但是我收到了

java.lang.ArrayIndexOutOfBoundsException
Caused by: java.lang.ArrayIndexOutOfBoundsException

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

最佳答案

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

关于android - 将字符串动态插入到Android中的字符串数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6938291/

相关文章:

Java - ArrayList<Integer>[][] 可能吗?

android - Camera.takePicture 抛出 RunTimeException

c++ - C++中的动态缓冲区类型?

c - atoi返回值

javascript - 减少不删除正确的数组项

arrays - 数组排序错误 : "Binary operator ' <' cannot be applied to two ' Int ?' operands"

Android gradle 单独的 res/文件夹构建

android - 服务在被杀死后不会重新启动,即使在 Return_STICKY 之后

java - 如何更改为我可以删除的 ValueEventListener?

python - 使用动态编程技术调试 Google KickStart "2022"Round D 最大增益问题