【问题标题】:Getting SQLite database and storing it in an array of objects获取 SQLite 数据库并将其存储在对象数组中
【发布时间】:2011-10-10 12:51:59
【问题描述】:
我正在查看 Android SDK 中的 Notes 应用示例。我想学习的不是使用 CursorAdapter 传递给 ListAdpater/ListView 来整理,而是想知道如何自己处理数据;尤其是 ArrayList 形式。
在示例中,便笺基本上具有 id、标题和正文。我想知道如何查询 SQLite 数据库并使用它返回的游标来收集数据并创建我将调用 Note 的对象的对象实例,该对象具有 id、title 和 body 的参数。我最终想将所有这些对象存储到一个 ArrayList 中进行管理。我只是不确定如何处理光标。
这是一个非常笼统的问题,但我只需要有人指出我正确的方向。
【问题讨论】:
标签:
android
sqlite
object
arraylist
android-cursor
【解决方案1】:
我可能不明白你的问题,但你需要查询你的数据库,然后将游标数据添加到 ArrayList?
List<String> pointsList = new ArrayList<String>();
database = openOrCreateDatabase("favorites", SQLiteDatabase.OPEN_READWRITE, null);
if(database!=null)
{
c= database.rawQuery(QUERY, null);
c.moveToFirst();
while(c.isAfterLast()==false)
{
pointsList.add(c.getInt(c.getColumnIndex("id")); // do the same for other columns
c.moveToNext();
}
}
database.close();
c.close();
【解决方案2】:
其实我是在玩了之后自己想出来的。所以我意识到使用cursor.getColumnIndex("name_of_column") 将返回列的索引,以便在cursor.getInt(cursor.getColumnIndex("_id")); 等命令中使用。我所要做的就是使用 for 循环遍历整个列表并使用 cursor.moveToNext() 遍历收集的行。在我发布这个问题后,我想出了这一分钟。 :)
【解决方案3】:
这可能对你有帮助,
public ArrayList<ArrayList<Object>> getAllRowsAsArrays()
{
// create an ArrayList that will hold all the data collected from
// the database.
ArrayList<ArrayList<Object>> dataArrays = new ArrayList<ArrayList<Object>>();
// This is a database call that creates a "cursor" object.
// The cursor object store the information collected from the
// database and is used to iterate through the data.
Cursor cursor;
try
{
// ask the database object to create the cursor.
cursor = db.query(
TABLE_NAME,
new String[]{TABLE_ROW_ID, TABLE_ROW_ONE, TABLE_ROW_TWO},
null, null, null, null, null
);
// move the cursors pointer to position zero.
cursor.moveToFirst();
// if there is data after the current cursor position, add it
// to the ArrayList.
if (!cursor.isAfterLast())
{
do
{
ArrayList<Object> dataList = new ArrayList<Object>();
dataList.add(cursor.getLong(0));
dataList.add(cursor.getString(1));
dataList.add(cursor.getString(2));
dataArrays.add(dataList);
}
// move the cursor's pointer up one position.
while (cursor.moveToNext());
}
}
catch (SQLException e)
{
Log.e("DB Error", e.toString());
e.printStackTrace();
}
// return the ArrayList that holds the data collected from
// the database.
return dataArrays;
}