hay i used the SimpleCursorAdapter from implement the data on the spinner.its going well. also to get data i used following code:
Cursor cursor = (Cursor) (spncomapnayname.getSelectedItem());
if (cursor != null) {
companyselected = cc.getString(cc.getColumnIndex(db.COMPANY_NAME));
}
it is working well.but it is for the getting data from the spinner.but now i want to set particular data on spinner which was inserted by the user for update for normal ArrayAdapter spinner we used:
spinnername.setSelection(adapter1.getPosition(abc));
so i want to know how to set data from the database on spinner.
here is my code:
cursor = db.getProductName();
adapter1 = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, cursor, new String[] { DB_Database.PRODUCT_NAME }, new int[] { android.R.id.text1 });
adapter1.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spnproduct.setAdapter(adapter1);
purchaseproduct = purchasebundle.getString("clickedpurchaseproductname");
if(!purchaseproduct.equals("null")|| !purchaseproduct.equals("")) {
System.out.println("purchaseproduct" + purchaseproduct);
String mypurchaseproduct=purchaseproduct;
ArrayAdapter myAdap = (ArrayAdapter) spnproduct.getAdapter();
int spinnerPosition = myAdap.getPosition(mypurchaseproduct); // set the default according to value
spnproduct.setSelection(spinnerPosition);
}
here i get data from bundle.i want to retrive data on Spinner.the data is populated from SimpleCursorAdapter
First Get Selected Value From Cursor and store into mString Variable and then use below code for display this selected value into Spinner.
if (!mString.equals("null") || !mString.equals("")) {
String myString = mString; // the value you want the position for
ArrayAdapter<String> myAdap = (ArrayAdapter<String>) mSpn1.getAdapter(); // cast to an ArrayAdapter
int spinnerPosition = myAdap.getPosition(myString);
// set the default according to value
mSpn1.setSelection(spinnerPosition);
}
You can do something like this:
Cursor c = (Cursor)parent.getItemAtPosition(pos);
int id = c.getInt(c.getColumnIndexOrThrow("columm_name"));
or to get a String
String name=c.getString(c.getColumnIndexOrThrow("columm_name"));
Related
I'm populating a spinner with a number of records from my SQlite database using the following code:
DBHelper db = new DBHelper(getBaseContext());
Cursor cursor_clients = db.select("clients", "_id, name", "ORDER BY name"); // table, fields, filter/order
String[] columns = new String[] { "name" };
int[] to = new int[] { android.R.id.text1 };
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, cursor_clients, columns, to, 0);
mAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner spnClients = (Spinner) findViewById(R.id.spnClients);
spnClients.setAdapter(mAdapter);
It works great, and I can use
spnAcademias.getSelectedItemId();
To get the _id of the selected record. My problem is: How to select an item on this spinner by the _id?
I have the _id of the row I want, I want it to show this row selected, and not the first row coming from the query.
Doing more research I ended up with the solution here: setSelection on Spinner based on rowId
I thought maybe there was a native solution without a loop, but there is not.
Solution:
public void setSpinnerItemById(Spinner spinner, int _id)
{
int spinnerCount = spinner.getCount();
for (int i = 0; i < spinnerCount; i++)
{
Cursor value = (Cursor) spinner.getItemAtPosition(i);
long id = value.getLong(value.getColumnIndex("_id"));
if (id == _id)
{
spinner.setSelection(i);
break;
}
}
}
If you're able to just as easily get the text value of the row you are looking for, then try the solution here, and more specifically the top comment on it: Set selected item of spinner programmatically
Use the following: spinnerObject.setSelection(INDEX_OF_CATEGORY2).
...
... I also found a way of getting the index without needing to loop through the adapter. I used the following mySpinner.setSelection(arrayAdapter.getPosition("Category 2"));
Right now I am almost done writing my app. All I need is a bit help on getting the selected String value from a spinner populated from my database by a simple cursor adapter. I am not sure how I can get the String from my spinner and pass it to a different cursor and use the string in a query, that will populate depending on the first choice of the spinner, and so on with other spinners.
Here is the code I am using for one of my spinners.
vType = (Cursor) DataBaseHelper.getPowersportsType();
this.startManagingCursor(vType);
SimpleCursorAdapter scaType = new SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item,
vType,
new String [] {DataBaseHelper.POWERSPORTS_TYPE},
new int[] {android.R.id.text1});
scaType.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
vTypeSpinner = (Spinner) findViewById(R.id.typeSpinner);
vTypeSpinner.setAdapter(scaType);
And this is my query for the next spinner in my xml layout
static String MakeWhere = "POWERSPORTS_TYPE=?";
public static Cursor getPowersportsMake(){
return myDataBase.query(POWERSPORTS_TABLE,
new String [] {POWERSPORTS_ID, POWERSPORTS_MAKE},
MakeWhere,
null,
POWERSPORTS_MAKE,
null,
null);
}
Any comments or suggestions are welcomed.
to get the item selected you need to set the onItemSelectedListener
then in your onItemtSelected all you would do is
String selection = vTypeSpinner.getSelectedItem().toString();
I have a spinner which is populated with DB values returned in form of Cursor.but it always have first value as selected. What I need is to have a "None" value instead od ffirst DB value. I know we can do this when we have hardcoded strings but how can i do it with Cursor..??
My code for spinner -
Cursor c = listNamesDbHelper.fetchAllUserLists();
startManagingCursor(c);
Log.i(TAG, "cursor list names--->>" + c.getCount());
// create an array to specify which fields we want to display
String[] from = new String[c.getCount() + 1];
from = new String[]{listNamesDbHelper.KEY_LIST_NAME};
//from[0] = "None";
// create an array of the display item we want to bind our data to
int[] to = new int[]{R.id.ModifyTaskListNameItem};
// create simple cursor adapter
/*SimpleCursorAdapter adapter =
new SimpleCursorAdapter(this, R.layout.choose_list_modify_task, c, from, to );
adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );*/
// get reference to our spinner
CustomSpinnerItemsAdapter adapter = new CustomSpinnerItemsAdapter(this,c,from,to);
Spinner s = (Spinner) findViewById( R.id.spinnerListSelection );
s.setAdapter(adapter);
Thanks in advance,
Ray
I need to create a drop down list (spinner) in eclipse for Android whereby the drop down options can be created by the user.
To do this I've created a SQLiteDatabase, which I want to convert into a string array to be put into an array adapter, which can then be fed into the spinner.
Database details are:
DATABASE_NAME = "carddb"
DATABASE_TABLE = "cardtable"
Then the column I wish to read the values from is:
KEY_CARDDETAILS = "_carddetails";
Here is my code so far, adapted from another question on this site (Link: how to get the database value to a String array in android(sqlite Database))
myDB = cardtable.this.openOrCreateDatabase("carddb", MODE_PRIVATE, null);
Cursor cardcursor = cardDB.rawQuery("SELECT * FROM cardtable");
String[] cardstringarray = new String[cardcursor.getCount()];
cardcursor.moveToFirst();
int counter = 0;
while(cardcursor.moveToNext()){
String carddetailss = cardcursor.getString(cardcursor.getColumnIndex("NAME"));
cardstringarray[counter] = carddetailss;
counter++;
}
I'm getting an error under "myDB" and "cardtable", both errors saying they cannot be resolved into a variable!
PLEASE HELP!
Use this code
String[] displayName={};
ArrayList<String> List=new ArrayList<String>();
myDB = cardtable.this.openOrCreateDatabase("carddb", MODE_PRIVATE, null); Cursor cardcursor = cardDB.rawQuery("SELECT * FROM cardtable");
String[] cardstringarray = new String[cardcursor.getCount()];
cardcursor.moveToFirst();
int counter = 0;
while(cardcursor.moveToNext()){
String carddetailss = cardcursor.getString(cardcursor.getColumnIndex("NAME"));
List.add(carddetailss);
counter++;
}
if(List != null){
listEmail=(ListView)findViewById(R.id.listEmail);
listEmail.setVisibility(view.VISIBLE);
displayName=(String[])List.toArray(new String[0]);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, displayName);
// Assign adapter to ListView
listEmail.setAdapter(adapter);
}
This is work for you. Use spinner instead of listView.
I have created a simple Spinner binding it to a SimpleCursorAdapter. I'm populating the SimpleCursorAdapter with a list of towns from a content provider.
When I go to save the users selection I'm planning on saving the row id that is being populated into my SimpleCursorAdapter.
I'm using the following code to get the ID.
townSpinner.getSelectedItemId();
What I can not figure out is how best to set the selection when I pull back up the saved item.
The following code works but it only sets selection by position number.
townSpinner.setSelection(2);
Should I just create a loop to determine the correct position value based on Id?
long cityId = Long.parseLong(cursor.getString(CityQuery.CITY_ID));
for (int i = 0; i < citySpinner.getCount(); i++) {
long itemIdAtPosition2 = citySpinner.getItemIdAtPosition(i);
if (itemIdAtPosition2 == cityId) {
citySpinner.setSelection(i);
break;
}
}
I think you've answered your own question there!
Just write your own setSelectionByItemId method using the code you posted
Example:
DB:
public Cursor getData() {
SQLiteDatabase db = getReadableDatabase();
String sql = "select ID _id, Name from MyTable order by Name ";
Cursor c = db.rawQuery(sql, null);
c.moveToFirst();
return c;
}
Activity:
Cursor myCursor = db.getData();
SimpleCursorAdapter adapter1 = new SimpleCursorAdapter(
this,
android.R.layout.simple_spinner_item,
myCursor,
new String[] { "Name" }, new int[] { android.R.id.text1 }, 0);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mySpinner.setAdapter(adapter1);
for(int i = 0; i < adapter1.getCount(); i++)
{
if (adapter1.getItemId(i) == myID )
{
mySpinner.setSelection(i, false); //(false is optional)
break;
}
}
Android Spinner set Selected Item by Value
The spinner provides a way to set the selected valued based on the position using the setSelection(int position) method. Now to get the position based on a value you have to loop thru the spinner and get the position. Here is an example
mySpinner.setSelection(getIndex(mySpinner, myValue));
private int getIndex(Spinner spinner, String myString){
int index = 0;
for (int i=0;i<spinner.getCount();i++){
if (spinner.getItemAtPosition(i).equals(myString)){
index = i;
}
}
return index;
}
If you are using an ArrayList for your Spinner Adapter then you can use that to loop thru and get the index. Another way is is to loop thru the adapter entries
Spinner s = (Spinner) findViewById(R.id.spinner_id);
for(i=0; i < adapter.getCount(); i++) {
if(myString.trim().equals(adapter.getItem(i).toString())){
s.setSelection(i);
break;
}
}