我正在做一个 android 项目,我遇到了一个问题,问题是:
Arraylist empty when I return it.
这是我的java代码:
ArrayList<ArrayList<Object>> container = new ArrayList<ArrayList<Object>>();
ArrayList<Object> itemRow = new ArrayList<Object>();
JSONObject jsonObj = new JSONObject(result);
JSONArray allElements = jsonObj.getJSONArray("Table");
Log.i("allElements", "" + allElements);
for (int i = 0; i < allElements.length(); i++) {
itemRow.add(allElements.getJSONObject(i).getString("ParentName").toString());
itemRow.add(allElements.getJSONObject(i).getString("ParentEmailID").toString());
itemRow.add(allElements.getJSONObject(i).getString("ParentContact").toString());
itemRow.add(allElements.getJSONObject(i).getString("ParentAddress").toString());
itemRow.add(allElements.getJSONObject(i).getString("ParentProfilePictureName").toString());
itemRow.add(allElements.getJSONObject(i).getString("StudentName").toString());
Log.i("itemRow", "itemRow at index: " + i + ", " + itemRow);
container.add(((i*2)/2), itemRow);
itemRow.clear();
}
return container;
在这段代码中,我有两个 Arraylist,一个用于包含所有元素,另一个用于存储单行元素。这些 Arraylist 是从 JSONArray 加载的,一切正常,我可以从项目行(采用单行的 Arraylist)打印数据并存储到主 Arraylist(容器)中。
但是当我返回这个 Arraylist(容器)并在 logcat 中打印时,它显示空的 Arraylist,如
[[], [], [], [], []].
我不明白为什么会这样,请帮我解决这个问题。
谢谢。
最佳答案
因为你做了,它仍然引用添加到container
的对象
itemRow.clear();
你可能想重新初始化它
itemRow = new ArrayList<Object>();
关于java - 返回时数组列表为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11206057/