我需要从我的 SQLite 数据库获取所有信息并将其存储在数组列表中,或者如果有更好的方法则以其他方式存储。我的数据库有 6 列,以下是我尝试提取数据并将其存储在 Arraylist 索引中的方法;
db.open();
for(int i = 0; i<= amount; i++)
{
Cursor c = db.fetchAllNotes();
if (c.moveToFirst())
{
do {
mid = c.getString(0);
place =c.getString(1);
info =c.getString(2);
coordl1 =c.getString(3);
coordl2 =c.getString(4);
colour =c.getString(5);
//code here to store each string in an Array index
mapSetupList.add(mid,place,info,coordl1,coordl2,colour);
}while (c.moveToNext());
}
}
db.close();
我知道如何创建一个数组列表,但我不知道如何在一个索引中存储 6 个字符串,我尝试过 2D Arraylists,但这似乎太复杂了,我认为这不是正确的方法去做吧。有没有更好的方法来做到这一点,如果没有,如何使用 Arraylists 来完成?
最佳答案
如何创建一个自己定义的对象,将所有列包装为属性?
public class Foo {
private int id; // alternative to id column in db
private String type;
private String date;
...
public void setId(int id) { // setter
this.id = id;
}
public int getId() { // getter
return this.id;
}
}
然后创建ArrayList<Foo>
现在您可以简单地将数据从 SQLite 保存到 ArrayList 中:
public void store() {
Cursor c = null; // first declare and initialise appropriate objects
ArrayList<Foo> foos = new ArrayList<Foo>();
Foo member = null;
try {
c = db.rawQuery(query, whereArgs); // perform query
if (c.moveToFirst()) { // move cursor to first row because implicitly
do { // cursor is position before first row
member = new Foo(); // for each row create new Foo
member.setId(c.getInt(0)); // initialise properties
member.setType(c.getString(1));
member.setDate(c.getString(2));
...
foos.add(member); // add Foo into ArrayList
} while (c.moveToNext()); // it moves cursor to next row
}
}
finally { // in finally block release datasource(s), cursor(s)
if (c != null) {
c.close();
}
if (db != null && db.isOpen()) {
db.close();
}
}
}
注意:我推荐这种方法。它清晰、安全、有效。工作完成后不要忘记释放任何数据源、游标,以避免通常抛出的异常,例如游标已打开、数据库已关闭等。
更新:
I am unsure about the class example, with the defined object and getters and setters, can you please elaborate before I try this? Thank you!!
因此,getter 和 setter 是“一般”用于操作对象属性以保留封装的方法 - 在 OOP 中非常重要。 Setter 用于初始化属性,getter 用于获取对象的属性。
现在我为您编写了将数据从 sqlite 存储到 ArrayList 的方法示例。有这样一行:
member.setId(c.getInt(0));
哪里setId(c.getInt(0))
是 Foo 对象 的 setter ,以一个整数作为参数,现在使用此方法,您将使用来自 Cursor
的数据填充 id 值。 .
关于android - 如何将 SQLite 中的数据存储在 2D Arraylist 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15325508/