Dong
Dong

Reputation: 3

Android Java Refresher no click

I have this method in my MainActivity.java which shows the current time

// date format
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
// current date time
String now = format.format(Calendar.getInstance().getTime());

private void displayCurrentTime(String ctime) {
    TextView priceTextView = (TextView) findViewById(R.id.current_time);
    priceTextView.setText(ctime);
}

public void currentTime(View v) {
    displayCurrentTime(now);
}

And this is the Button in my activity_main.xml where the time does display.

        <Button
        android:id="@+id/current_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="currentTime"
        android:paddingBottom="40dp"
        android:paddingTop="40dp"
        android:text="now"
        android:textSize="20dp" />

So if I click on the button with my mobile device the current time and date will be displayed.

My Questions is if it is possibly to show the time without the onClick event,

and if the time can update itself, because now it shows only the current time at which I pressed the button.

Upvotes: 0

Views: 67

Answers (2)

Nigel Gamboa
Nigel Gamboa

Reputation: 36

i use this timer to refresh any function, but remember to use the functions of the life cycle of activity to restart or stop the timer.

@Override
protected void onResume() {
    refreshData(1);
    super.onResume();
}

@Override
protected void onPause() {
    refreshData(0);
    super.onPause();
}

@Override
protected void onStop() {
    refreshData(0);
    super.onStop();
}

@Override
protected void onDestroy() {
    refreshData(0);
    super.onDestroy();
}

declare timer:

Timer timer = new Timer();

and the function timer:

    public void refreshData(int status) {
    if(status == 1){
        timer = new Timer();
        final Handler handler = new Handler();
        TimerTask doAsynchronousTask = new TimerTask() {       
            @Override
            public void run() {
                handler.post(new Runnable() {
                    public void run() {       
                        //call to the function
                    }
                });
            }
        };
        //time to timer 5 seg
        timer.schedule(doAsynchronousTask, 0, 5000);
    }
    else{
        timer.cancel();
    }
}

hope this help.. :)

Upvotes: 1

Pranava Sheoran
Pranava Sheoran

Reputation: 529

You can use a timer and update the button text every time the timer fires. http://developer.android.com/reference/java/util/Timer.html
You can keep the timer interval at 1 second to update the button time. Not sure if this is the best way but it will definitely work.

Upvotes: 0

Related Questions