Using a variable to switch to a certain spinner item - android

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

Related

How to get items from Listadapter in android?

I have a Listadapter wherein there are 4 different strings, and storing them to my listview. Now I want to get all the items from one of those strings and parse it to "date", so how can I able to populate my calendar dates from my listadapter?
Following the codes:
// Get User records from SQLite DB
ArrayList<HashMap<String, String>> eventsList = controller.getAllevents();
// If users exists in SQLite DB
if (eventsList.size() != 0) {
// Set the User Array list in ListView
ListAdapter adapter = new SimpleAdapter(CalendarActivity.this, eventsList, R.layout.calendar_event_list, new String[]{TAG_PID,
TAG_EVENTTITLE,TAG_EVENTSTART,TAG_EVENTEND},
new int[]{R.id.pid, R.id.eventname, R.id.eventstart, R.id.eventend});
ListView myList = (ListView) findViewById(android.R.id.list);
myList.setAdapter(adapter);
String eventstart = adapter.toString(); //I got null exception here..
Date edate = ParseDate(eventstart);
if (caldroidFragment != null) {
caldroidFragment.setBackgroundResourceForDate(R.color.Green, edate);
caldroidFragment.refreshView();
}
}
If you want to fetch an item from your adapter you can use
adapter.getItem(position);
which will return the item at the specified position. In your case, that method will return the HashMap<String, String> at the specified position:
Example:
/* adapter.getCount() returns the count of how many items
(HashMaps, in your case) that is represented in this adapter. */
for(int i = 0; i < adapter.getCount(); i++){
HashMap<String, String> myHashMap = adapter.getItem(i);
//"myKey" is the key that you provided, when mapping your key-values
String myVal = myHashMap.get("myKey");
Date edate = ParseDate(myVal);
/* Handle your Date object here. I'm just printing it to the console
in this example. */
System.out.println("Item at position " + i + " " + edate.toString());
}
Problem solved! Just simply put inside the loop and change the 'position' variable into the variable that handles the loop e.g for (int i = 0; i < eventsList.size(); i++) change adapter.getItem(position) to adapter.getItem(i)

Converting an ArrayAdapter to a List<String>

I have an array adapter(string), and would like to convert it to a List<String>, but after a little googling and a few attempts, I am no closer to figuring out how to do this.
I have tried the following;
for(int i = 0; i < adapter./*what?*/; i++){
//get each item and add it to the list
}
but this doesn't work because there appears to be no adapter.length or adapter.size() method or variable.
I then tried this type of for loop
for (String s: adapter){
//add s to the list
}
but adapter can't be used in a foreach loop.
Then I did some googling for a method (in Arrays) that converts from an adapter to a list, but found nothing.
What is the best way to do this? Is it even possible?
for(int i = 0; i < adapter.getCount(); i++){
String str = (String)adapter.getItem(i);
}
Try this
// Note to the clown who attempted to edit this code.
// this is an input parameter to this code.
ArrayAdapter blammo;
List<String> kapow = new LinkedList<String>(); // ArrayList if you prefer.
for (int index = 0; index < blammo.getCount(); ++index)
{
String value = (String)blammo.getItem(index);
// Option 2: String value = (blammo.getItem(index)).toString();
kapow.add(value);
}
// kapow is a List<String> that contains each element in the blammo ArrayAdapter.
Use option 2 if the elements of the ArrayAdapter are not Strings.

Unable to fetch data from Hashmap properly

I have an Arraylist of HashMap. Each HashMap element contains two columns: column name and corresponding value. This HashMap will be added into a ListView with 3 TextView.
I populate the ArrayList as follows, and then assign that to an adapter in order to display it:
ArrayList<HashMap<String, String>> list1 = new ArrayList<HashMap<String, String>>();
HashMap<String, String> addList1;
for (int i = 0; i < count; i++) {
addList1 = new HashMap<String, String>();
addList1.put(COLUMN1, symbol[i]);
addList1.put(COLUMN2, current[i]);
addList1.put(COLUMN3, change[i]);
list1.add(addList1);
RecentAdapter adapter1 = new RecentAdapter(CompanyView.this,
CompanyView.this, list1);
listrecent.setAdapter(adapter1);
}
.
Now on listItemClick, the fetched data is of the different form at different time.
For eg. My list contains following data:
ABC 123 1
PQR 456 4
XYZ 789 7
i.e. When I log the fetched string after clicking 1st list item, I get one of the several outputs:
{1=ABC ,2=123 ,3=1}
{First=ABC ,Second=123 ,Third=1}
{1=123 ,0=ABC ,2=1}
and even
{27=123 ,28=1 ,26=ABC}
Initially I used:
int pos1 = item.indexOf("1=");
int pos2 = item.indexOf("2=");
int pos3 = item.indexOf("3=");
String symbol = item.substring(pos1 + 2,pos1 - 2).trim();
String current = item.substring(pos2 + 2, pos3 - 2).trim();
String change = item.substring(pos3 + 2, item.length() - 1).trim();
Then for the 4th case, I have to use:
int pos1 = item.indexOf("26=");
int pos2 = item.indexOf("27=");
int pos3 = item.indexOf("28=");
String symbol = item.substring(pos1 + 3, item.length() - 1).trim();
String current = item.substring(pos2 + 3, pos3 - 3).trim();
String change = item.substring(pos3 + 3, pos1 - 3).trim();
So that I get ABC in symbol and so on.
But, by this approach, application loses it's reliability completely.
I also tried
while (myVeryOwnIterator.hasNext()) {
key = (String) myVeryOwnIterator.next();
value[ind] = (String) addList1.get(key);
}
But it's not giving proper value. Instead it returns random symbol for eg. ABC or PQR or XYZ.
Am I doing anything wrong?
Thanks in advance!
The HashMap's put function does not insert value in specific order. So the best way is to put the keyset of the HashMap in a ArrayList and use the ArrayList index in retrieving the value
ArrayList<HashMap<String, String>> list1 = new ArrayList<HashMap<String, String>>();
HashMap<String, String> addList1;
ArrayList<String> listKeySet;
for (int i = 0; i < count; i++) {
addList1 = new HashMap<String, String>();
addList1.put(COLUMN1, symbol[i]);
addList1.put(COLUMN2, current[i]);
addList1.put(COLUMN3, change[i]);
listKeySet.add(COLUMN1);
listKeySet.add(COLUMN2);
listKeySet.add(COLUMN3);
list1.add(addList1);
RecentAdapter adapter1 = new RecentAdapter(CompanyView.this,
CompanyView.this, list1);
listrecent.setAdapter(adapter1);
}
And when retrieving use
addList1.get(listKeySet.get(position));
Here, the arraylist listKeySet is just used to preserve the order in which the HashMap keys are inserted. When you put data in HashMap insert the key into the ArrayList.
I don't think using HashMap for this purpose is a good idea. I would implement Class incapsulating your data like
class myData {
public String Column1;
public String Column2;
public String Column3;
// better idea would be making these fields private and using
// getters/setters, but just for the sake of example these fields
// are left public
public myData(String col1, String col2, String col3){
Column1 = col1;
Column2 = col2;
Column3 = col3;
}
}
and use it like
ArrayList<myData> list1 = new ArrayList<myData>();
for (int i = 0; i < count; i++) {
list1.add(new myData(symbol[i], current[i], change[i]));
}
//no need to create new adapter on each iteration, btw
RecentAdapter adapter1 = new RecentAdapter(CompanyView.this,
CompanyView.this, list1);
listrecent.setAdapter(adapter1);
You will need to make changes in your adapter to use myData instead of HashMap<String,String>, of course.

sort array list from second item android

i have a array list for using it in spinner ,i have first value i spinner as title and i want to sort array list from second item in the spinner but i dont know how to do this i am using below trick but it sort whole array list including first item which is title so how to statr sorting from second item...
my code is below...
// this is my title ie. "provincia"
String select2= "Provincia";
if(!estado1.contains(select2)){
estado1.add(select2);
}
for (int i = 0; i < sitesList1.getEstado().size(); i++)
{
if(!estado1.contains(sitesList1.getEstado().get(i)))
{
estado1.add(sitesList1.getEstado().get(i));
Collections.sort(estado1);
}
use below code for show it in spinner...
final ArrayList<String> estado1 = MainMenu.barrio1;
final Spinner estado11 = (Spinner) findViewById(R.id.Spinner04);
ArrayAdapter<String> adapterbarrio = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, estado1)
estado11.setAdapter(adapterbarrio);
Why not remove the title / only add the title after the list has been sorted?
How about this
List<String> list = new ArrayList<String>();
// Fill list
String title = list.get(0);
list.remove(0);
Collections.sort(list);
list.add(0, title);
One way would be to split the arraylist like
estado1.subList(1,estado1.size()-1);
This would return a sublist excluding your title.
Use bubble sort! and start at index = 1!
final ArrayList<String> estado1;
for(int i=1; i<estado1.size() ; i++) {
for(int c=i; c<estado.size() ; c++) {
if(estado1.get(i).compareTo(estado1.get(c)))
{
String temp = estado1.get(i);
estado1.remove(i);
estado1.add(i, estado1.get(c));
estado1.remove(c);
estado1.add(c, temp);
}
}
}
PS: very bad performance

How to set spinner selection by id not position

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

Categories

Resources