uttara_shekar
uttara_shekar

Reputation: 37

Android: Display time using simpledateformat

I am trying to display the time that a user enters, either in a toast or using a basic println command. If the time is in the correct format, I want to enter it in a database along with the current time.

Here is what I have so far:

public void addListenerOnButton ()
{
    spinner_hours = (Spinner)findViewById(R.id.hours);
    spinner_minutes = (Spinner)findViewById(R.id.minutes);
    btnSubmit = (Button) findViewById(R.id.btnSubmit);
    btnSubmit.setOnClickListener(new OnClickListener() {

        @Override
          public void onClick(View v) {
            Date time;
            String enteredTime= String.valueOf(spinner_hours.getSelectedItem())+String.valueOf(spinner_minutes.getSelectedItem())+"00";
            SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");

            try {
                time= format.parse(enteredTime);
                System.out.println(enteredTime);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        //   Toast.makeText(MainActivity.this,
        //              "Your alarm has been set for : " + time,
        //                  Toast.LENGTH_SHORT).show();

          }
    });
}

If I put the toast (commented below) inside the try block, it doesnt show up when I run the app. If I put a system.out.println it does not print anything. How do I print the entered time?

Also, I want to enter the current time in the same format ("HH:mm:ss") in the database. Any ideas on how to do that?

Upvotes: 0

Views: 211

Answers (2)

vinothp
vinothp

Reputation: 10069

First try to print the value got from the Spinner

 System.out.println(spinner_hours.getSelectedItem().toString());
 System.out.println(spinner_minutes.getSelectedItem().toString());

If this doesn't has any value then the problem is here.

Upvotes: 0

Flávio Faria
Flávio Faria

Reputation: 6605

It's probably throwing an exception, since System.out.println should work. Try replacing this:

String enteredTime= String.valueOf(spinner_hours.getSelectedItem())+String.valueOf(spinner_minutes.getSelectedItem())+"00";

by this:

String enteredTime= String.valueOf(spinner_hours.getSelectedItem())+ ":" + String.valueOf(spinner_minutes.getSelectedItem())+":00";

It seems you're missing the : between hour and minutes and before 00 and the parsing is failing.

Upvotes: 1

Related Questions