【发布时间】:2016-05-08 04:16:01
【问题描述】:
我想知道是否可以基于 sqlite 从 android 数据库中获取一种特定类型的数据。
假设我有一个包含“类别”和“标题”行的表,我想获得一个字符串数组,其中包含与给定类别匹配的那些类别的“标题”。
例如:
Title Category
A spam
B important
C spam
给定“垃圾邮件”,我想得到一个类似的字符串数组
S = {A,C}
有没有办法做到这一点?
请注意,我对数据库非常陌生。
提前致谢。
编辑:
我实际上是在尝试查询
mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE,
KEY_BODY, KEY_CATEGORY}, KEY_CATEGORY + "=" + category, null, null, null, KEY_CATEGORY);
但它返回一个光标,我需要一个像这里这样的 SimpleCursorAdapter 来格式化
SimpleCursorAdapter notes =
new SimpleCursorAdapter(this, R.layout.notes_row, notesCursor, from, to);
mList.setAdapter(notes);
从哪里到哪里是:
String[] from = new String[] { NotesDbAdapter.KEY_TITLE };
int[] to = new int[] { R.id.text1 };
最终编辑:
终于成功了,这段代码由@ELITE提供
Cursor cursor = mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE, KEY_BODY, KEY_CATEGORY}, KEY_CATEGORY + "=?", new String[]{category}, null, null, KEY_CATEGORY);
ArrayList elements = new ArrayList();
while(cursor.moveToNext()) {
elements.add(cursor.getString(cursor.getColumnIndex(KEY_TITLE)));
}
// use elements variable,
// here you'll get ["A", "C"]
SimpleCursorAdapter notes =
new SimpleCursorAdapter(this, R.layout.notes_row, cursor, from, to);
mList.setAdapter(notes);
【问题讨论】:
-
你是怎么做到的????
-
@ELITE 我实际上正在尝试使用查询
mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE, KEY_BODY, KEY_CATEGORY}, KEY_CATEGORY + "=" + category, null, null, null, KEY_CATEGORY);但这会返回一个光标,我需要一个 SimpleCursorAdapter 进行格式化。为了清楚起见,我将更新主要帖子。
标签: android database sqlite fetch