Pleas Help: get index of element from spinner

Put problem concerning Views, Layouts and other XML-Resources (like AndroidManifest) here.

Pleas Help: get index of element from spinner

Postby dreamdelerium » Thu Jan 07, 2010 3:34 am

hello everyone. I hope some one can assist me. when my main activity starts a secondary activity, it passes a string variable. i want that variable to set the value in a spinner (the spinner has a list of elements from an xml file). the problem is that i only see examples of setting a spinners selected value by specifying its index. as i dont know the index, but rather the element, how do i do this? is there a way to search the spinners elements and get the index?

example:
in spinner1, the choices are
<element 1>
<element 2>
<element 3>
<element 4>

how do i set the setSelection to <element 3> if i dont know the index of <element 3>. i do know the string value (which is <element 3>)

thanks for your help
dreamdelerium
Developer
Developer
 
Posts: 30
Joined: Fri Jan 01, 2010 11:19 pm

Top

Postby jwei512 » Thu Jan 07, 2010 11:57 pm

So I've seen this problem come up before... but with no actual working answer... so I think the only way you can do it is by writing a method like this:

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2.  
  3.  
  4. public int getIndexFromElement(ArrayAdapter adapter, String element) {
  5.  
  6.       for(int i = 0; i < adapter.size(); i++) {
  7.  
  8.             if(adapter.getItem(i).equals(element)) {
  9.  
  10.                   return i;
  11.  
  12.             }
  13.  
  14.       }
  15.  
  16.       return 0;
  17.  
  18. }
  19.  
  20.  
  21.  
  22.  
Parsed in 0.033 seconds, using GeSHi 1.0.8.4


Again, it's not optimal... but I think this should work...

Anyone have a better method?
- jwei

http://thinkandroid.wordpress.com
Examples, Code, and Tutorials
jwei512
Senior Developer
Senior Developer
 
Posts: 135
Joined: Mon Jul 27, 2009 9:35 pm
Location: Palo Alto, CA

Postby dreamdelerium » Fri Jan 08, 2010 4:04 am

thanks. ill give it a try
dreamdelerium
Developer
Developer
 
Posts: 30
Joined: Fri Jan 01, 2010 11:19 pm

Postby icobasco » Wed Jan 13, 2010 10:38 am

jwei512 wrote:
Again, it's not optimal... but I think this should work...

Anyone have a better method?


Hi, I agree with you and it's a dirty job that you have to do by yourself.
Usually spinners/combos deal with ids and not values....so unfortunatly you are right :(
Obviously in my opinion!
User avatar
icobasco
Senior Developer
Senior Developer
 
Posts: 108
Joined: Thu Jun 04, 2009 11:12 am
Location: Italy

Top

Return to View, Layout & Resource Problems

Who is online

Users browsing this forum: No registered users and 8 guests