Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populating Spinner From SQLite Database Android

I'm attempting to make a dynamic drop down that will be filled by a SQLite table. I have a Cursor object which I can pull the data I need from. I've been able to accomplish loading the values into the drop down with the code below:

Spinner s = (Spinner) findViewById(R.id.spinner);
    ArrayAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    s.setAdapter(adapter);

    try{
        Cursor cursor = getAccounts();
        int accountnameIndex = cursor.getColumnIndexOrThrow(ACCOUNT_NAME);
        if(cursor.moveToFirst()){
            do{
                adapter.add(cursor.getString(accountnameIndex));
            } while(cursor.moveToNext());
        }
    } finally {
        MintLink.close();
    }

My problem is that I need the a selection from the drop down to also contain the RowID of the item selected. I need to be able to select one item and have access to the value of that item in the back end. For example, think of a drop down in HTML. Each drop down selection has it's own hidden value that is pulled. I need this value to be hidden for me to allow me to know which ID they choose.

like image 382
crv Avatar asked Feb 03 '10 23:02

crv


People also ask

What is cursor in Android with example?

Cursors are what contain the result set of a query made against a database in Android. The Cursor class has an API that allows an app to read (in a type-safe manner) the columns that were returned from the query as well as iterate over the rows of the result set.


1 Answers

This is an old question but the first one I found when figuring out this issue. Here is a detailed explanation with full source which may cut some legwork.

The answer is indeed to use a SimpleCursorAdapter which handles a list of strings but also has special handling for a matched ID field that gets returned when a row is selected. The key to making this work is to know the two following obscure bits of information:

1) When creating the cursor make sure the query returns a field titled "_id". This field need not be displayed anywhere but it's value will be passed back when a list item is selected.

2) When creating a SimpleCursorAdapter you need to supply the TextView layout IDs where the row text will be placed. If using the android supplied layout android.R.layout.simple_spinner_item the text id you need to use is android.R.id.text1.

Main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        ></Spinner>
</RelativeLayout>

Activity code:

public class TesterActivity extends Activity {
public Context mContext;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // just for this example:
    // create database table with an id field and a text field and add some data
    class MyDBHelper extends SQLiteOpenHelper {
        public MyDBHelper(Context context) {
            super(context, "someDB", null, 2);
        }
        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL("CREATE TABLE someTable (someIDF INTEGER, someTextF TEXT)");
        }
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS someTable");
            onCreate(db);
            db.execSQL("INSERT INTO someTable (someIDF, someTextF) VALUES (54, 'Some text')");
            db.execSQL("INSERT INTO someTable (someIDF, someTextF) VALUES (99, 'Some more text')");
            db.execSQL("INSERT INTO someTable (someIDF, someTextF) VALUES (173, 'Even more text')");
        }
    }
    SQLiteDatabase db = new MyDBHelper(this).getWritableDatabase();

    // get a cursor from the database with an "_id" field
    Cursor c = db.rawQuery("SELECT someIDF AS _id, someTextF FROM someTable", null);

    // make an adapter from the cursor
    String[] from = new String[] {"someTextF"};
    int[] to = new int[] {android.R.id.text1};
    SimpleCursorAdapter sca = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, c, from, to);

    // set layout for activated adapter
    sca.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 

    // get xml file spinner and set adapter 
    Spinner spin = (Spinner) this.findViewById(R.id.spinner1);
    spin.setAdapter(sca);

    // set spinner listener to display the selected item id
    mContext = this;
    spin.setOnItemSelectedListener(new OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id){
            Toast.makeText(mContext, "Selected ID=" + id, Toast.LENGTH_LONG).show();
        }
        public void onNothingSelected(AdapterView<?> parent) {}
        });
    }
}
like image 64
MindSpiker Avatar answered Sep 20 '22 01:09

MindSpiker