Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting String value from a Spinner backed by CursorAdapter from SQL query in Android

my code here is horribly wrong, and i'm not sure how you would properly do this. i have a Spinner which is populated from a SQLite database query through a CursorAdapter. i need to get the text (value) of the currently selected item. i tried this garbage:

((Cursor)prdSpn.getItemAtPosition(prdSpn.getSelectedItemPosition())).getString(prdSpn.getSelectedItemPosition())

to get the text, but it crashes every time. what's the proper way to do this? here's some additional code that may be relevant:

/// qc defined above as a SimpleCursorAdapter
/////////setup product selection spinner from db
prdSpn = (Spinner)findViewById(R.id.prd_spn);
Cursor prdCur = null;
try {
    prdCur = mDb.query(smsDbSchema.ProductSchema.TABLE_NAME, null, null, null, null, null, null);
} catch(Exception e) {
    Log.e("smsdb", e.toString());
}
prdCur.moveToFirst();
startManagingCursor(prdCur);
qc = new SimpleCursorAdapter(
    this,
    android.R.layout.simple_spinner_item,
    prdCur,
    new String[] {smsDbSchema.ProductSchema.COLUMN_NAME},
    new int[] {android.R.id.text1}
);
qc.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
prdSpn.setAdapter(qc);
like image 637
moonlightcheese Avatar asked Feb 07 '11 22:02

moonlightcheese


1 Answers

Code similar to the following works for me...

Cursor theCursor = qc.getCursor();
String theString = theCursor.getString(theCursor.getColumnIndex(<your column name here>));

EDIT by moonlightcheese:

implementation:

Cursor theCursor = (Cursor)prdSpn.getSelectedItem();
Log.e("spnERRtest", "Item: " + theCursor.getString(theCursor.getColumnIndex(smsDbSchema.ProductSchema.COLUMN_NAME)));
//theCursor.getString(theCursor.getColumnIndex(smsDbSchema.ProductSchema.COLUMN_NAME)).contains("CAR")
like image 98
Squonk Avatar answered Sep 18 '22 23:09

Squonk