How to update a TextView on ButtonClick with Spinner(s) values

Posted by source.rar on Stack Overflow See other posts from Stack Overflow or by source.rar
Published on 2010-06-14T19:02:38Z Indexed on 2010/06/14 20:32 UTC
Read the original article Hit count: 171

Filed under:
|

Hi,

I am trying to populate a TextView based on the current selected options in 3 Spinner(s) but cant seem to figure out how to retrieve the selected values from the Spinners to invoke the update function with. Here is my current code (quite messy but I'm just learning Java :)),

public class AgeFun extends Activity {
private String[] dayNames;
private String[] yearArray;
private final static int START_YEAR = 1990;
private static TextView textDisp;
private Button calcButton; 
private static Spinner spinnerDay, spinnerYear, spinnerMonth;
private static ArrayAdapter<?> monthAdapter, dayAdapter, yearAdapter;
private int year, month, day;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    year = 2000;
    month = 1;
    day = 1;
    textDisp = (TextView) findViewById(R.id.textView1);
    calcButton = (Button) findViewById(R.id.button);
    calcButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            // Perform action on clicks
            AgeFun.updateAge(year, month, day);
        }
    });

    // Month spinner
    spinnerMonth = (Spinner) findViewById(R.id.spinnerFirst);
    monthAdapter = ArrayAdapter.createFromResource(
            this, R.array.monthList, android.R.layout.simple_spinner_item);
    monthAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinnerMonth.setAdapter(monthAdapter);

    // Day spinner
    dayNames = new String[31];
    for(int i =1; i <= 31; ++i)
    {
        dayNames[i-1] = Integer.toString(i);
    }
    spinnerDay = (Spinner) findViewById(R.id.spinnerSecond);
    dayAdapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, dayNames);
    spinnerDay.setAdapter(dayAdapter);

    // Year spinner
    yearArray = new String[40];
    for(int i =0; i < 40; ++i)
    {
        yearArray[i] = Integer.toString(START_YEAR+i);
    }
    spinnerYear = (Spinner) findViewById(R.id.spinnerThird);
    yearAdapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, yearArray);
    spinnerYear.setAdapter(yearAdapter);

    updateAge(2000,1,1);
}

private static void updateAge(int year, int month, int day) {
    Date dob = new GregorianCalendar(year, month, day).getTime();
    Date currDate = new Date();

    long age = (currDate.getTime() - dob.getTime()) / (1000 * 60 * 60 * 24) / 365;
    textDisp.setText("Your are " + Long.toString(age) + " years old");
}

}

Any help with this would be great.

TIA

© Stack Overflow or respective owner

Related posts about java

Related posts about android