Reputation: 289
I'm wondering if it is possible to fetch one specific type of data from an android database, based on sqlite.
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.
For example:
Title Category
A spam
B important
C spam
And given "spam", I want to get a String array like
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 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
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);
Upvotes: 0
Views: 754
Reputation: 5950
Iterator over the cursor and store the result in ArrayList
or Vector
and then use it.
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
Upvotes: 1
Reputation: 1457
Use the query()
of SQLiteDatabase
class like this:
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query("<name of the table>", new String[]{}, "Category=?", new String[]{"spam"}, null, null, null);
Upvotes: 0