Posted By

variable3 on 05/02/11


Tagged

get database values item using selected android Spinneradd


Versions (?)

Android Spinner(get selected Item)


 / Published in: Java
 

  1. In xml----<Spinner android:id="@+id/spnState" android:layout_width="wrap_content" android:layout_height="wrap_content"></Spinner>
  2.  
  3. //Bind values to spinner through an array
  4. String[] items = new String[] {"Karnataka", "Orissa", "Andhrapradesh"};
  5. Spinner spinner;
  6.  
  7. spinner = (Spinner)this.findViewById(R.id.spnState);
  8. ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, items);
  9. adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
  10. spinner.setAdapter(adapter);
  11.  
  12. //Bind values to spinner through databases
  13.  
  14. //--Write a query to get all the values in a column in a table
  15. public Cursor columnValues() throws SQLException {
  16. SQLiteDatabase db;
  17. return db.query(TABLE_NAME, new String[] { ID, KEY_NAME }, null, null, null, null, KEY_NAME + " ASC", null);
  18. }
  19. //--then in activity under button click write,
  20. Cursor cursor = db.columnValues();
  21. startManagingCursor(cursor);
  22.  
  23. // create an array to specify which fields we want to display
  24. String[] from = new String[] { DBAdapter.KEY_NAME };
  25. // create an array of the display item we want to bind our data to
  26. int[] to = new int[] { android.R.id.text1 };
  27.  
  28. Spinner spinner = (Spinner) this.findViewById(R.id.spinnerID);
  29. SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
  30. android.R.layout.simple_spinner_item, cursor, from, to);
  31. adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
  32. spinner.setAdapter(adapter);
  33.  
  34. //How to get selected values from spinner
  35.  
  36. Spinner spinner = (Spinner) findViewById(R.id.spinnerID);
  37. String selectedItem;
  38. Cursor cc = (Cursor)(spinner.getSelectedItem());
  39. if (cc != null) {
  40. selectedItem = cc.getString(cc.getColumnIndex(db.KEY_NAME));
  41. }

Report this snippet  

You need to login to post a comment.