Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Set Spinner Start point

This is probably a simple straight forward thing to do for some.

I have this code...

SQLiteDatabase db = dbs.getReadableDatabase(); 
String SQL = "SELECT * FROM Table"; 
final Cursor cursor = db.rawQuery(SQL, null);
    array_spinner1[0] = "Select:";
    while (cursor.moveToNext()) {
      array_spinner1[i]= cursor.getString(1) + " - " + cursor.getString(2);
      i ++;
    } 
    final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,                  android.R.layout.simple_spinner_item, array_spinner1);
    s1.setAdapter(adapter);

I populate the array and everything runs fine. However, i want to start the position of the spinner not at the first item(Select). I want it to start where the item in the cursor = 'here' for example. I hope i made sense?

To put it into context in 'Table' column 1 is age range from and column 2 is age range to. so in the spinner i get 0-5, 6-10, 11-20 etc

and what i want to do is start the spinner selected at 11-20 if the user's d.o.b makes him that age....? I know setSelection would select a certain value, but i need to work out the correct one for the users age?

So i basically want to know how to work that out and populate select the spinner correctly, thanks

like image 202
Beginner Avatar asked Feb 24 '11 14:02

Beginner


1 Answers

The Spinner class inherits setSelection(int position, boolean animate) from AbsSpinner. Call that method with the position of your desired default (and false for the animated bit). You only need to iterate through your list of possible values to check for conditions, so maybe I don't understand where your difficulty lies?

Reading through this a second time I get the impression that this is isn't really an Android question. What you're looking for is how to see if a given date of birth places a user in a given age bracket. I've seen age math done in Joda here: How do I calculate someone's age in Java?

From there it's a matter of seeing if the age falls within your given range.

boolean isInRange(Years age, int start, int end) {
  int intAge = age.getYears();
  if (intAge >= start && intAge <= end) {
    return true;
  } else {
    return false;
  }
}

One more addition to my answer here. If you dont' want to deal with running Joda on Android, here's another possibility for calculating age using only the standard Java components. See the third post.

http://www.coderanch.com/t/391834/java/java/there-better-way-calculate-age

Per your request for an example, here is SimpleDateFormat for date strings.

String dateString = "04/02/2004";
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
Date parsedDate = format.parse(dateString, 1);
like image 125
Mike Yockey Avatar answered Oct 12 '22 09:10

Mike Yockey