Note that there are some explanatory texts on larger screens.

plurals
  1. POSet position of android spinner from database id
    text
    copied!<p>I have <a href="https://github.com/wholcomb/smoke_tracker/tree/add-tabs" rel="nofollow">an app</a> that allows users to list habits and then create goals timers to wait until they exercise that habit again. For the goal creation activity there is a spinner of habits to choose from. I am using the following to populate it:</p> <pre><code>protected void onCreate(Bundle bundle) { ⋮ mHabitSelect = (Spinner) findViewById(R.id.habit); String[] queryCols = new String[] { HabitTable.TABLE_HABIT + "." + HabitTable.COLUMN_ID, HabitTable.COLUMN_NAME }; String[] from = new String[] { HabitTable.COLUMN_NAME }; int[] to = new int[] { R.id.label }; Cursor cursor = getContentResolver().query(MyHabitContentProvider.HABITS_URI, queryCols, null, null, null); SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, R.layout.habit_select_row, cursor, from, to, 0); mHabitSelect.setAdapter(mAdapter); mHabitSelect.setOnItemSelectedListener(this); } </code></pre> <p>The <code>onItemSelected</code> method has an id parameter that seems to be the database id.</p> <pre><code>public void onItemSelected(AdapterView&lt;?&gt; parent, View view, int position, long id) { long databaseId = id; } </code></pre> <p>This gives me the value to save in the database, but I need a method to set the spinner to the saved habit from the database when loading the editing interface.</p> <pre><code>private void fillData(Uri uri) { String[] projection = { GoalTable.COLUMN_HABIT_ID, GoalTable.COLUMN_TIME, GoalTable.TABLE_GOAL + "." + GoalTable.COLUMN_DESCRIPTION }; Cursor cursor = getContentResolver().query(uri, projection, null, null, null); if (cursor != null) { cursor.moveToFirst(); int habitId = cursor.getInt(cursor.getColumnIndexOrThrow(GoalTable.COLUMN_HABIT_ID)); //mHabitSelect.setSelection(habitId); ⋮ } } </code></pre> <p>I don't have to iterate through the results to figure out which database id is at which position in the spinner, do I?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload