alois.wirkes
alois.wirkes

Reputation: 369

Get item selected of a spinner when its filled up from a database cursor

In my Android App I hava a layout with to Spinners. What I want to do is given a selected item from the first spinner, fill up the second one.

The first spinner is filled up from a cursor (result of a database query) like this:

Spinner combo1 = (Spinner) findViewById(R.id.combo1);
mDbH.open();
Cursor c1 = null;
c1 = mDbH.consulta4();
startManagingCursor(c1);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,android.R.layout.simple_spinner_item,c1,new String[] {"nombre"},new int[] {android.R.id.text1});
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
combo1.setAdapter(adapter);

This works fine! The problem comes inside my event listener:

combo1.setOnItemSelectedListener(new OnItemSelectedListener(){
    public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
        String est = String.valueOf(combo1.getSelectedItem());
        int idEst = (int) id;
        Log.e("est",est);
        Log.e("idEst",""+idEst);
        mDbH.open();
        Cursor c = null;
        c = mDbH.consulta5(idEst,est);
        SimpleCursorAdapter adapter2 = new SimpleCursorAdapter(getApplicationContext(),android.R.layout.simple_spinner_item,c,new String[] {"nombre"},new int[] {android.R.id.text1});
        adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        combo1.setAdapter(adapter2);
    }

    public void onNothingSelected(AdapterView<?> arg0) {}

});

Because, in the LogCat the line Log.e("est",est); shows this:

10-25 09:48:50.390: E/est(3462): android.database.sqlite.SQLiteCursor@40625638

And of course, that value is not in my database and the second cursor is empty and the spinner doesn't fill up with anything!! So, this is my question, how do you get the item selected of a spinner when is filled up from a database? I also tried out:

String est = combo1.getSelectedItem().toString();

and

String est = parentView.getItemAtPosition(position).toString();

but the result is the same!! Am I doing something wrong? Please help!

Thanks!

Upvotes: 1

Views: 2495

Answers (1)

Mohamed_AbdAllah
Mohamed_AbdAllah

Reputation: 5322

Since your Spinner was filled out using a SimpleCursorAdapter, getItemAtPosition & getSelectedItem will return a Cursor reference. Use:

Cursor c=(Cursor) combo1.getSelectedItem();
String est=c.getString(c.getColumnIndex("nombre");

Same works for getItemAtPosition(position)

Upvotes: 3

Related Questions