Search code examples
androidtoasttimepicker

Getting time using time picker and show it using Toast, code doesn't work


I was trying a simple code which shows time selected using Toast and time picker but nothing happens and there was no errors, the same also happens in date picker.

Here is the code:

public class MainActivity extends ActionBarActivity {
TimePicker tP;

public  void clickMe(View V){
    Toast.makeText(this,"Time Selected: " + (tP.getCurrentHour()) + ":" + tP.getCurrentMinute(),Toast.LENGTH_LONG).show();
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tP = (TimePicker)findViewById(R.id.timePicker);
}

I've only made a time picker in the layout and an onclick:clickMe.

Note: This was supposed to work because I've taken this code from an instructor.

Edit:

Here is layout:

<TimePicker
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/timePicker"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:onClick="clickMe" />

Edit 2

Sorry, maybe i should have elaborated my question:

Why isn't my code not working?

for now i don't need the solution i just want the reason why this didn't work?

thanks.


Solution

  • EDIT 2: Btw make sure you press part that shows selected time, and the toast will pop up

    EDIT add following line into XML if you want it to be clickable:

     android:clickable="true"
    

    ======================================================================= Alternative solution: Try adding OnClickListener in onCreate method, just after you call findViewById, and remove onClick attribute from the layout..

        tm = (TimePicker) findViewById(R.id.timepciker_id);
        tm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(this,"Time Selected: " + (tP.getCurrentHour()) + ":" + tP.getCurrentMinute(),Toast.LENGTH_LONG).show();
            }
        });