Search code examples
positionspinnerandroid-cursoradapter

How to set Spinner selection by value, using CursorAdapter


I have a spinner I'm populating from the database. I want to choose which item from the list is selected by default. I need to find out what item in the list (CursorAdapter) has the value "Default Away" and set that to the selected value.

    Spinner away_team_spinner = (Spinner)findViewById(R.id.away_team_spinner);
    DatabaseHelper db = new DatabaseHelper(this);
    Cursor team_list = db.getTeams(p_game_level);
    startManagingCursor(team_list);

    String[] team_name = new String[]{colTeamName};
    int[] to = new int[]{android.R.id.text1};
    SimpleCursorAdapter adapter =
      new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, team_list, team_name, to );
    adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
    away_team_spinner.setAdapter(adapter);

    //// HERE IS WHERE MY ERRORS START ////

    Log.i("NEW_GAME","Before set arrayadapter");
    CursorAdapter adapter_choose = (CursorAdapter)away_team_spinner.getAdapter();
    Log.i("NEW_GAME","Before set setSelection");
    away_team_spinner.setSelection(adapter_choose.getPosition("Default Away"));

This is the "solution" I found by searching on this web site. However, I cannot use "getPosition" with CursorAdapter object. I tried ArrayAdapter, but then the line after "Before set arrayadapter" comment errors with "android.widget.SimpleCursorAdapter cannot be cast to android.widget.ArrayAdapter". What am I doing wrong? Thanks.


Solution

  • have you thought about running a for loop until you find the position then set the adapter position that way? ill draft up some code then test it, i'm doing something similar

    and well this just did the trick, enjoy!

        int cpos = 0;
    
        for(int i = 0; i < simpleCursorAdapter.getCount(); i++){
          cursor.moveToPosition(i);
          String temp = cursor.getString((your column index, an int));
          if ( temp.contentEquals(yourString)){
            Log.d("TAG", "Found match");
            cpos = i;
            break;
          }
        }
        spinner.setSelection(cpos);