Search code examples
androideclipseandroid-edittexttimepickerandroid-timepicker

display results from timePicker in a editText field


I can't seem to get the results from a timePicker into an editText field. I followed the example in the Android training guide and I can see the results from the timePicker in a log but I can't figure out how to display them in a text field (tvEndTime).

public class Setup extends Activity {

....

private final TextView tvEndTime = (TextView) findViewById(R.id.textViewEndTime);

....

public static class TimePickerFragment extends DialogFragment
    implements TimePickerDialog.OnTimeSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current time as the default values for the picker
        final Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);

        // Create a new instance of TimePickerDialog and return it
        return new TimePickerDialog(getActivity(), this, hour, minute,
        DateFormat.is24HourFormat(getActivity()));
    }

    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        // Do something with the time chosen by the user
        Log.i(TAG, Integer.toString(hourOfDay) + ":" + Integer.toString(minute));
        tvEndTime.setText(Integer.toString(hourOfDay) + ":" + Integer.toString(minute));
    }
}

// show the end time timePicker dialog box fragment when user clicks buttonEndTime
public void showTimePickerDialog(View v) {
    DialogFragment newFragment = new TimePickerFragment();
    newFragment.show(getFragmentManager(), "timePicker");
}  

....

At the tvEndTime.setText() line, I get an Eclipse error "Cannot make static reference to the non static field tvEndTime". But I can't declare the tvEndTime as static because then I get the error at the tvEndTime declaration. What am I doing wrong?


Solution

  • Write this code inside onClick() event of any view you are using:

                Calendar mcurrentTime = Calendar.getInstance();
                int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
                int minute = mcurrentTime.get(Calendar.MINUTE);
    
                TimePickerDialog mTimePicker;
                mTimePicker = new TimePickerDialog(CurrentActivity.this, new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
                        editText.setText( selectedHour + ":" + selectedMinute);
                    }
                }, hour, minute, true);
                mTimePicker.setTitle("Select Time");
                mTimePicker.show();
    

    Or:

    Simply change the way you set the text to EditText by:

    tvEndTime.setText(selectedHour+" : "+selectedMinute);
    

    Correction: Make your TextView tvEndTime as a class variable for class Setup