How to set spinner selection by id not position - android

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;
}
}

Related

Getting a selected row from an Arraylist in Android

I have an arraylist populated with data from a cursor, I would like to get a selected or single record from this list which I would need to pass as an intent, how possible can I achieve this.
private ArrayList<Insect> insectList(){
insects = new ArrayList<>();
if (cursor.getCount() > 0){
int count = 0;
while (cursor.moveToNext()){
if (count < quizActivity.ANSWER_COUNT){
count++;
insect = new Insect(cursor.getString(cursor.getColumnIndex(BugsContract.BugsEntry.COLUMN_FRIENDLYNAME)),
cursor.getString(cursor.getColumnIndex(BugsContract.BugsEntry.COLUMN_SCIENTIFICNAME)),
cursor.getString(cursor.getColumnIndex(BugsContract.BugsEntry.COLUMN_SCIENTIFICNAME)),
cursor.getString(cursor.getColumnIndex(BugsContract.BugsEntry.COLUMN_IMAGEASSET)),
Integer.parseInt(cursor.getString(cursor.getColumnIndex(BugsContract.BugsEntry.COLUMN_DANGERLEVEL)))
);
insects.add(insect);
Collections.shuffle(insects);
}
}
}
return insects;
}
I need to get a selected record from the Arraylist insects

How to position (select) a spinner on specific item by id with simplecursoradapter?

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"));

Using a variable to switch to a certain spinner item

I have:
a String array with an unknown length that's populated with unknown items (let's say fish, bird, cat)
an ArrayAdapter and a Spinner that displays the items
a variable that contains one unknown item from the string array (let's say cat)
I want to set the Spinner to the value from the variable (cat). What's the most elegant solution? I thought about running the string through a loop and comparing the items with the variable (until I hit cat in this example), then use that iteration's # to set the selection of the Spinner, but that seems very convoluted.
Or should I just ditch the Spinner? I looked around and found a solution that uses a button and dialog field: https://stackoverflow.com/a/5790662/1928813
//EDIT: My current code. I want to use "cow" without having to go through the loop, if possible!
final Spinner bSpinner = (Spinner) findViewById(R.id.spinner1);
String[] animals = new String[] { "cat", "bird", "cow", "dog" };
String animal = "cow";
int spinnerpos;
final ArrayAdapter<String> animaladapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, animals);
animaladapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
bSpinner.setAdapter(animaladapter);
for (Integer j = 0; j < animals.length; j++) {
if (animals[j].equals(animal)) {
spinnerpos = j;
bSpinner.setSelection(spinnerpos);
} else {
};
}
(Temporarily) convert your String array to a List so you can use indexOf.
int position = Arrays.asList(array).indexOf(randomVariable);
spinner.setSelection(position);
EDIT:
I understand your problem now. If your String array contains all unique values, you can put them in a HashMap for O(1) retrieval:
HashMap<String, Integer> map = new HashMap<String, Integer>();
for (int i = 0; i < animals.length; i++) {
map.put(animals[i], i);
}
String randomAnimal = "cow";
Integer position = map.get(randomAnimal);
if (position != null) bSpinner.setSelection(position);

How to Retrive proper data on Spinner from SimpleCursorAdpter in Android

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"));

how to select row in spinner for known rowid?

When i open Activity for EditRecord i want to select spinner row for adequate value in edited record
I find code like below, but its ok for few records in spinner, but when spinner.cursor contains many records i think its not right idea.
Is any other method to select spinner row for known rowid ?
Spinner spinner = (Spinner) findViewById(R.id.spinner);
spinner.setAdapter(new SimpleCursorAdapter(...));
for (int i = 0; i < spinner.getCount(); i++) {
Cursor value = (Cursor) spinner.getItemAtPosition(i);
long id = value.getLong(value.getColumnIndex("_id");
if (id == rowid) {
spinner.setSelection(i);
}
}
Why are you getting a cursor and looking p the column index every time? Simply do:
for (int i = 0; i < spinner.getCount(); i++) {
long id = spinner.getItemIdAtPosition(i);
if (id == rowid) {
spinner.setSelection(i);
}
}

Categories

Resources