Java 正在将重复值添加到ArrayList
我已经创建了一个自定义列表适配器,并且正在尝试从SQLite数据库中列出数据。“我的列表”正在输出正确数量的数据库记录,但已将最终的数据库项复制了许多倍,与数据库中的项目数量相同 我有以下代码:Java 正在将重复值添加到ArrayList,java,sqlite,arraylist,Java,Sqlite,Arraylist,我已经创建了一个自定义列表适配器,并且正在尝试从SQLite数据库中列出数据。“我的列表”正在输出正确数量的数据库记录,但已将最终的数据库项复制了许多倍,与数据库中的项目数量相同 我有以下代码: private class JSONParse extends AsyncTask<String, String, JSONArray> { @Override protected JSONArray doInBackground(String... args) {
private class JSONParse extends AsyncTask<String, String, JSONArray> {
@Override
protected JSONArray doInBackground(String... args) {
JSONArray arr = null;
db = new DatabaseHandler(getActivity());
arr = db.getSynced();
db.close();
DiaryItems diary = new DiaryItems();
try {
for (int i = 0; i < arr.length(); i++) {
JSONObject c = arr.getJSONObject(i);
String ass_id = c.getString(TAG_ASSID);
String time = c.getString(TAG_TIME);
String cname = c.getString(TAG_CNAME);
String cno = c.getString(TAG_CNO);
String type = c.getString(TAG_TYPE);
String complete = c.getString(TAG_COMPLETE);
System.out.println("ASS ID: " + ass_id); //works - prints ass_id 1->10
diary.setAss_id(ass_id);
diary.setTime(time);
diary.setCname(cname);
diary.setCno(cno);
diary.setType(type);
diary.setComplete(complete);
diaryList.add(diary);
}
for (int j = 0; j < diaryList.size(); j++) {
System.out.println("ASSIGN ID: " + diaryList.get(j).getAss_id());
//this prints this correct size of items, but the array only contains
//the values of the last item parsed in the JSON
}
} catch (JSONException e) {
e.printStackTrace();
}
return arr;
}
@Override
protected void onPostExecute(JSONArray array) {
if (dialog.isShowing()) {
System.out.println("Dismissed dialog");
dialog.dismiss();
}
if (diaryList != null) {
DiaryListAdapter adapter = new DiaryListAdapter(getActivity(), diaryList);
getListView().setAdapter(adapter);
}
}
}
您正在将同一个DiaryItems实例多次添加到列表中。您应该在循环的每个迭代中创建一个新的DiaryItems实例
改变
DiaryItems diary = new DiaryItems();
try {
for (int i = 0; i < arr.length(); i++) {
....
到
您已经实例化了DiaryItems diary=new DiaryItems;
在for循环之外。在循环中创建它,而不是每次循环结束时都添加它。尝试:
for (int i = 0; i < arr.length(); i++) {
DiaryItems diary = new DiaryItems();
..do stuff
}
而不是:
DiaryItems diary = new DiaryItems();
try {
for (int i = 0; i < arr.length(); i++) {
JSONObject c = arr.getJSONObject(i);
您已经在for循环外部实例化了日记对象,因此在每次迭代中最终都会设置相同的实例
DiaryItems diary = new DiaryItems();
try {
for (int i = 0; i < arr.length(); i++) {
JSONObject c = arr.getJSONObject(i);