Search code examples
androidsqlitespinnersimplecursoradapter

Populate spinner from simple cursor adapter


I have some trouble to populate spinner from sqlite database with simple cursor adapter. I must use simple cursor adapter not array adapter. My MainActivity, functions and xml files are as follows:

  public class MainActivity extends BaseActivity {


    private Spinner workerId = (Spinner) findViewById(R.id.spinner);

    c = getCursor();

    String[] columns = new String[]{Database.mylist};
    int[] to = new int[] { R.id.spinner };
    myAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, c, columns,to, 0);
    workerId.setAdapter(myAdapter);

    ..............
    ..............
    }

Function is below:

    public Cursor getCursor() {
    Cursor c = database.rawQuery("select * from " + Database.mylist + " where isCancel = 0", null);
    return c;
}

Xml file is below;

        MainActivity.xml


    <Spinner
        android:id="@+id/spinner"
        android:layout_width="match_parent"
        android:layout_marginTop="10dp"
        android:layout_marginLeft="5dp"
        android:layout_height="wrap_content" />

And when I run app the following screen displays. There is data but it seems empty. I have _id, name columns.

empty spinner

Thank you for your help.


Solution

  • Change

    int[] to = new int[] { R.id.spinner };
    

    to

    int[] to = new int[] { android.R.id.text1 };
    

    And you can read a little bit more about SimpleCursorAdapter here: Android: Using SimpleCursorAdapter to get Data from Database to ListView

    Also you are using Database.mylist as column name and table name as PPartisan pointed out in a comment.