我是java的android开发新手,我不明白一件事。 我需要从我的数据库中获取数据(没问题)并将其存储在Object的ArrayList中,但是当我放入elem时,下一个elememt将覆盖所有以前的数据。
public ArrayList<Task> getTaskList(){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(DB_TABLE,new String[]{DB_TITLE, DB_DESC},null,null,null,null,null);
ArrayList<Task> taskList = new ArrayList<>();
if (taskList == null)
taskList = new ArrayList<>();
while(cursor.moveToNext()){
int indexTitle = cursor.getColumnIndex(DB_TITLE);
int indexDesc = cursor.getColumnIndex(DB_DESC);
String title = cursor.getString(indexTitle);
String desc = cursor.getString(indexDesc);
Task task = new Task(title, desc);
taskList.add(task);
System.out.println("NOTRE LISTE CONTIENT");
for (Task taask : taskList){
System.out.println(taask.getTitle() + "-" + taask.getDescription());
}
}
cursor.close();
db.close();
return taskList;
}
Task.Java
public class Task {
private static String title;
private static String description;
public Task(){}
public Task(String title, String description){
this.title = title;
this.description = description;
System.out.println("NEW TASK: " + title + " " + description);
}
public String getTitle() { return this.title; }
public void setTitle(String title) { this.title = title; }
public String getDescription() { return this.description; }
public void setDescription(String description) { this.description = description; }
}
它打算打印:
test-tata potpot-eptept tata-tete test-teeest arr-arg
但打印:
你知道吗?我没有谢谢,但没有任何作用......谢谢。arr-arg arr-arg arr-arg arr-arg arr-arg
答案 0 :(得分:2)
问题出在您的Task
班级:
private static String title; private static String description;
static
关键字实质上意味着&#34;在所有实例之间共享此值&#34;。每当你创建一个&#34; new&#34; Task
实例,您更新title
和description
,这会更改Task
类所有实例的这些变量的值。
从两者中删除static
关键字。
private String title;
private String description;