问题
i'm having a problem with a Cursor and a SimpleCursorAdapter.
What i want to accomplish:
I have a database with 3 fields
_id | nickName | somethingelse
I want to select all nickNames distinctly and provide them in an AutoCompleteTextView.
Problem:
When doing the query (see below) i don't select the _id-field. That's why i get an error when trying to create the SimpleCursorAdapter because in the cursor there is no field "_id".
But if i select the "_id" in the query, the nickNames in the cursor won't be destinct anymore! Additionally a Cursor is not modifyable to my knowledge or is it?
So i figured out a workaround which works but is pretty bad programming style, because i'm doing double the work ... i just put the same data into another container and then use it. Isn't there a direct way for this? This is actually a simple task ... there must be a way to do this and i don't see it.
Here's the Code:
protected void onPrepareDialog(int id, final Dialog dialog)
{
switch(id)
{
case R.layout.database_feed:
/*get all distinct names in the Database */
Cursor cursor2 = mDatabase.rawQuery("SELECT DISTINCT nickName FROM highscore_table "+
"ORDER BY nickName COLLATE NOCASE", null);
/* I didn't find a simple way to set cursor2 in a
* CursorAdapter for the AutoCompleteTextView.
* this was my first try (does not work): */
/*((AutoCompleteTextView) dialog.findViewById(R.id.actvName)).setAdapter(
new SimpleCursorAdapter(this,android.R.layout.simple_dropdown_item_1line,
cursor2, new String[] { "nickName" },
new int[] { android.R.layout.simple_dropdown_item_1line } )
); */
/*this is my workaround ... it works but it's horrible*/
LinkedList<String> llsNames = new LinkedList<String>();
for(cursor2.moveToFirst(); !cursor2.isAfterLast(); cursor2.moveToNext())
{
llsNames.addLast(cursor2.getString(0));
}
((AutoCompleteTextView) dialog.findViewById(R.id.actvName)).setAdapter(new ArrayAdapter<String>(
this, android.R.layout.simple_dropdown_item_1line, llsNames
));
break;
default:
break;
}
}
Thanks for any help
回答1:
Have you tried:
SELECT _id, nickName FROM highscore_table GROUP BY nickName ORDER BY nickName COLLATE NOCASE
I'm not quite sure if this works in SQLite.
回答2:
You can write this way also
SELECT personid _id, nickName FROM highscore_table GROUP BY nickName ORDER BY nickName COLLATE NOCASE
give first field personid
as alias (rename) _id
来源:https://stackoverflow.com/questions/9808953/simplecursoradapter-wont-work-because-of-missing-id