How to get the values from DB in spinner - android

How to get values into the spinner from the DB. I want to display values or datas on UI from DB. Is it cursor necessary to use to populate the values onto the UI?

I just follow the things to get the values from database, when the spinner values changed by postion -
Java class
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
//set some adapter here
spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
public class MyOnItemSelectedListener implements OnItemSelectedListener
{
#SuppressWarnings("unused")
public void onItemSelected(AdapterView<?> parent,View view, int pos, long id)
{
try
{
switch(parent.getId())
{
case R.id.spinner2:
int selected_spinner_item_position=pos;
String expired_spinner_item =parent.getItemAtPosition(pos).toString();
if(selected_spinner_item_position==0)
{
//am just using simple cursor adapter here and getting the values from database using dh.fetchAll() when the position is 0
sc_adapter(dh.fetchAll());
spinnertemp = selected_spinner_item_position;
}
}
}
}
}
Database
public Cursor fetchAll()
{
SQLiteDatabase db = this.getReadableDatabase();
cursor = db.query(t1, new String[] {"_id",task, pname, prior, time, dateformat, duptitle,dupname}, "stat=0", null, null, null, prior);
return cursor;
}
Just do what you need like these steps.

How to populate a Spinner widget from a database
Follow it, its really simple.

yes, cursor is required to fetch result set object or data as result set. You can find solution from
Android Developers Blog

Related

How to pass the data in the database to a spinner

I'm creating a method to read all the information in the database and view it through a spinner here is the code i tried for this function
public Spinner loadArtist(){
SQLiteDatabase DB = getReadableDatabase();
String[] projection = {
ArtistMaster.Artist.ARTIST_NAME};
Cursor cursor = DB.query(
ArtistMaster.Artist.TABLE_ARTIST,
projection,
null,
null,
null,
null,
null);
Spinner itemIds = new ArrayList<>();
while(cursor.moveToNext()) {
long itemId = cursor.getLong(
cursor.getColumnIndex(ArtistMaster.Artist.ARTIST_NAME));
itemIds.setAdapter(itemId);
}
cursor.close();
return itemIds;
}
but it gives me an error in this line Spinner itemIds = new ArrayList<>();
Should i declare it as a list instead of spinner
itemIds should be defined as an ArrayList<Long>. A Spinner is a UI element and an ArrayList is a data structure. You will most likely need to map the data to your UI using an adapter of some sort, eg. an ArrayAdapter:
Spinner spinner = ... // findViewById, new Spinner() etc.
ArrayList<Long> itemIds = new ArrayList<>();
//... fill array with artist IDs
spinner.setAdapter(
new ArrayAdapter(
this, // Context, Activity etc.,
android.R.layout.simple_list_item_1, // Spinner TextView item resource ID
itemIds // Data set.
));
By default, ArrayAdapter will call Object#toString() on each data object in the collection.
I'd suggest that it would be easier if you used a Cursor Adpater as they are designed to be used with a Cursor and there is no need to generate arrays.
SimpleCursorAdapter being that, a simple but still pretty flexible adapter for use with Cursors.
The only issue is that a Cursor Adapter requires a column name specifically _id (BaseColumns._ID resolves to this (as used below)).
First have the following member variables (obviously names can be what you wish)
:-
Cursor mCursor;
SimpleCursorAdapter mAdapter;
Spinner spinner;
SQLiteDatabase db;
In the onCreate Method of the activity have
:-
spinner = this.findViewById(R.id.?????); //
db = ???????? (as per your existing code)
manageSpinner();
Have a method
:-
private void manageSpinner() {
mCursor = db.query(
ArtistMaster.Artist.ARTIST_NAME,
new String[]{"*","rowid AS " + BaseColumns._ID}, //<<<<<<<< adds _ID column (unless the table is a WITHOUT ROWID table, pretty unlikely)
null,null,null,null,null
);
if (mAdapter == null) {
mAdapter = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_1,
mCursor,
new String[]{"the_column"}, // column(s) from which to extract data
new int[]{android.R.id.text1}, // layout views into which the data is placed
0
);
spinner.setAdapter(mAdapter);
// You want want to do something when an Item in the spinner is clicked (this does nothing as it is)
spinner.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//........... do your stuff here
// notes
// id will be the id of the row
// cursor will be positioned, so you can access data from the cursor if needed
}
});
} else {
mAdapter.swapCursor(mCursor);
}
}
Override the activity's onResume (refresh the spinner when returning to activity as underlying data may have changed) and onDestroy (to close the Cursor) methods using
:-
#Override
protected void onDestroy() {
super.onDestroy();
mCursor.close();
}
#Override
protected void onResume() {
super.onResume();
manageSpinner();
}

Add a "Please Select" option to a Spinner in Android

I have a Spinner which is filled from a query using a SimpleCursorAdapter, this works fine... but now I need to put an option "Please Select" before all the items retrieved from the query, just for usability issues... but I'm not quite sure of how to do so... HELP please...
Here is my code...
private Spinner comboForm;
...
comboForm = (Spinner) findViewById(R.id.comboFormularios);
...
mDbH.abrir();
final Cursor cu = mDbH.consultaFormularios(idU);
if(cu.moveToFirst() == false){
cu.close();
mDbH.cerrar();
}else{
SimpleCursorAdapter adapter2 = new SimpleCursorAdapter(getApplicationContext(),R.layout.spinner,cu,new String[] {"nombre"},new int[] {R.id.textoCombo});
adapter2.setDropDownViewResource(R.layout.simple_spinner_dropdown_item);
comboForm.setAdapter(adapter2);
}
mDbH.cerrar();
...
comboForm.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parentView, View selectedItemView,int position, long id) {
idF = (int) id;
obtenerDatosRutas(idU,idF);
tabla.removeAllViews();
llenarTabla();
}
public void onNothingSelected(AdapterView<?> arg0) {}
});
Where mDbH is an instance of the class I'm using to manipulate the Database... as you can see the Spinner is filled up from Cursor resulting of the query consultaFormularios(idU)
When you create your cursor, one possible solution would be to use a SQL UNION and construct second SELECT that simply contains the label you need (adding hard-coded dummy fields for ordering).
Alternatively, and this is most likely the simplest solution. Instead of using a cursor adapter, use an array adapter and start by populating the array with your default value you want, then stick in all the items from your cursor. Something like,
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("Please select");
final Cursor cu = mDbH.consultaFormularios(idU);
while(cu.moveToNext()) {
arrayList.add(cu.getString(0)); // assuming you want a
//string from the first column
}
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, arrayList);
comboForm.setAdapter(spinnerArrayAdapter);

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!
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)

spinner selected item

I've been reading stuff about this for hours and still haven't figured out how to do it.
I managed to populate a spinner from a cursor reading the database and now I'm trying to get the selected item on the spinner to help fill a listview.
Here's my code:
Cursor cursorpf = DatabaseHelper.getPFunc();
startManagingCursor(cursorpf);
Spinner spinnerpf = (Spinner) findViewById(R.id.spinner1);
String[] frompf = new String[] { "Designacao" };
int[] topf = new int[] { android.R.id.text1 };
SimpleCursorAdapter scaPFunc = new SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item, cursorpf, frompf, topf);
scaPFunc
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerpf.setAdapter(scaPFunc);
spinnerpf.setOnItemSelectedListener(new MyOnItemSelectedListener());
final String stringpf = MyOnItemSelectedListener.getSelected();
long id = spinnerpf.getSelectedItemId();
String stringpf = String.valueOf(id);
DatabaseHelper.setPF(stringpf);
MyOnItemSelectedListener class:
public class MyOnItemSelectedListener implements OnItemSelectedListener {
private static String selected = "";
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
selected = String.valueOf(id);
Toast.makeText(parent.getContext(), "Escolha: " + selected, Toast.LENGTH_LONG).show();
}
#SuppressWarnings("unchecked")
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
The toast on this class returns the cursor position. Now, I know I must compare it against the database to get the value I want, but I just can't do it. Would you please help me out?
Thanks in advance.
Edit:
Guys, would you help me out?
I managed to get the selected item by implementing the code above, but it happens that the listview is only filled when the app starts. When I select something on the spinner, nothing happens. :|
If you want to retrieve selected item from database, just pass the fourth argument of onItemSelected (id) to you SQL query. It's the row id of the record, aka _ID.

Android how to get selected item from data driven spinner

Newbie question. I'm using a SimleCursorAdapter to populate a spinner from an SQLite table, as shown in the Android dev docs:
Spinner list=(Spinner)findViewById(R.id.cboModel);
SimpleCursorAdapter ModelAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item, model,
new String[] {"Drug"},
new int[] {android.R.id.text1});
ModelAdapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
list.setAdapter(ModelAdapter);
list.setOnItemSelectedListener(onModelSelect);
I've set up a listener, but I can't figure out how to get the selected item text, it pulls up the SQLiteCursor, not the actual text in the spinner.
private AdapterView.OnItemSelectedListener
onModelSelect= new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?>
parent, View view, int position, long id) {
ModelName = parent.getSelectedItem().toString();
android.util.Log.w("OnItemSelect.cboModel", ModelName);
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
};
Google turns up the question on several message boards, but no answers, so it appears to be a common newbie question. It may be painfully obvious to some, but if you could point me in the right direction I would appreciate it. Thank you.
Since the selected item is a Cursor, you can easily get the value by calling getString with the index of the column in the original database query that you used to populate the Spinner.
String spinnerString = null;
Cursor cc = (Cursor)(yourSpinner.getSelectedItem());
if (cc != null) {
spinnerString = cc.getString(
cc.getColumnIndex("Drug"));
}
This technique definitely works when the Spinner is populated from the database. I have not tried it with a resource array.
Figured it out... get the id, then make a DB query:
String id_string = String.valueOf(id);
thismodel=Pkmodel.getById(id_string, dbModel);
ModelName=thismodel.getDrug();

Categories

Resources