[英]Fetch specific data from android database sqlite
I'm wondering if it is possible to fetch one specific type of data from an android database, based on sqlite. 我想知道是否有可能基于sqlite从android数据库中获取一种特定类型的数据。
Let's say I have a table with rows "Category" and "Title" and I want to get a String array containing the "Title" of those categories matching a given one. 假设我有一个表,其中包含行“ Category”和“ Title”,并且我想获得一个String数组,其中包含与给定类别匹配的那些类别的“ Title”。
For example: 例如:
Title Category
A spam
B important
C spam
And given "spam", I want to get a String array like 并给定“垃圾邮件”,我想得到一个String数组,例如
S = {A,C}
Is there a way to do this? 有没有办法做到这一点?
Please note that I'm very new to databases. 请注意,我是数据库的新手。
Thanks in advance. 提前致谢。
EDIT: 编辑:
I'm actually trying with a query 我实际上正在尝试查询
mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE,
KEY_BODY, KEY_CATEGORY}, KEY_CATEGORY + "=" + category, null, null, null, KEY_CATEGORY);
But it returns a Cursor and I need a SimpleCursorAdapter like here for formatting 但是它返回一个游标,我需要像这里的SimpleCursorAdapter进行格式化
SimpleCursorAdapter notes =
new SimpleCursorAdapter(this, R.layout.notes_row, notesCursor, from, to);
mList.setAdapter(notes);
where from and to are: 从哪里到:
String[] from = new String[] { NotesDbAdapter.KEY_TITLE };
int[] to = new int[] { R.id.text1 };
FINAL EDIT: 最终编辑:
It finally worked, with this code provided by @ELITE 终于成功了,使用@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);
Iterator over the cursor and store the result in ArrayList
or Vector
and then use it. 在光标上进行迭代,并将结果存储在
ArrayList
或Vector
,然后使用它。
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)));
}
cursor.close();
// use elements variable,
// here you'll get ["A", "C"]
SimpleCursorAdapter notes =
new SimpleCursorAdapter(this, R.layout.notes_row, elements, from, to);
mList.setAdapter(notes);
Hope it'll work. 希望它能工作。
For more details refer this question 有关更多详细信息,请参阅此问题
Use the query()
of SQLiteDatabase
class like this: 像这样使用
SQLiteDatabase
类的query()
:
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query("<name of the table>", new String[]{}, "Category=?", new String[]{"spam"}, null, null, null);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.