Using SimpleCursorAdapter with Spinner?

I have a db with a table "mytable" containing 2 columns "id", "sampletext" I want to request different sampletext and feed values ​​on Spinner using SimpleCursorAdapter.

that's what they tried

String[] cols=new String[]{"sampletext"}; int[] lbls=new lbls[]{android.R.id.text1}; mycursor=sdb.query(true,"mytable", cols,null,null,null,null,null,null); sca=new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, mycursor, cols,lbls,0); sca.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spn.setAdapter(sca); 

When I ran this, I get an error in line 4: id does not exist. when I changed the first line to "id", the counter filled with id values. But I need a “sample text”, what am I doing wrong? Rate any suggestions

+4
source share
3 answers
 what am i doing wrong 

you did not read the documentation ...

There are two row arrays with columns: first in use in the query, the second in the Adapter constructor (you used only one array for both)

first tells sqlite which columns should be moved to Cursor, the second tells Adapter which ones should be shown / displayed in Views on the same line ...

Next, CursorAdapter requires Cursor with a column named _id

So now it’s pretty obvious that we have to do this:

 String[] queryCols=new String[]{"_id", "sampletext"}; String[] adapterCols=new String[]{"sampletext"}; int[] adapterRowViews=new int[]{android.R.id.text1}; mycursor=sdb.query(true,"mytable", queryCols,null,null,null,null,null,null); sca=new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, mycursor, adapterCols, adapterRowViews,0); sca.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spn.setAdapter(sca); 
+12
source

Here is a raw request example. Note that the first identifier column returned by the request must be marked as _id .

MyDatabase.java:

 public class MyDatabase extends SQLiteAssetHelper { ... public Cursor getListNamesForDropDown() { SQLiteDatabase db = getReadableDatabase(); String sql = "select ID _id, Name from MyTable order by Name "; Cursor c = db.rawQuery(sql, null); c.moveToFirst(); return c; } 

MyActivity.java:

  @Override public void onCreate(Bundle savedInstanceState) { .... Cursor cursorTest = db.getListNamesForDropDown(); android.widget.SimpleCursorAdapter adapter = new android.widget.SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, cursorTest, new String[] {"Name"}, new int[] {android.R.id.text1}, 0); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinnerTest.setAdapter(adapter); 
+1
source
 android.widget.SimpleCursorAdapter adapter = new android.widget.SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, cursor, new String[] { DBOpenHelper.ACCOUNT_BANK }, new int[] { android.R.id.text1 }, 0); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
0
source

Source: https://habr.com/ru/post/1446398/


All Articles