Reputation: 115
This is the new class code:
package com.test.webservertest;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Timer;
/**
* Created by tester on 8/27/2015.
*/
public class TimerCounter extends Activity
{
TextView timerTextView;
long startTime = 0;
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {
@Override
public void run() {
long millis = System.currentTimeMillis() - startTime;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
timerTextView.setText(String.format("%d:%02d", minutes, seconds));
timerHandler.postDelayed(this, 500);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timerTextView = (TextView) findViewById(R.id.textView3);
Button b = (Button) findViewById(R.id.button);
b.setText("start");
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Button b = (Button) v;
if (b.getText().equals("stop")) {
timerHandler.removeCallbacks(timerRunnable);
b.setText("start");
} else {
startTime = System.currentTimeMillis();
timerHandler.postDelayed(timerRunnable, 0);
b.setText("stop");
}
}
});
}
@Override
public void onPause() {
super.onPause();
timerHandler.removeCallbacks(timerRunnable);
Button b = (Button)findViewById(R.id.button);
b.setText("start");
}
}
And in the MainActivity.java file in the onCreate i did:
private TimerCounter tc;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tc = new TimerCounter();
tc.onCreate(savedInstanceState);
}
Now when running the program i'm getting exception in the TimerCounter class on the line:
super.onCreate(savedInstanceState);
savedInstanceState null
What i want to do is either using the button in the TimerCounter class or without the button when running my program the timer will start.
How can i do it using the button and without the button ?
I added to the MainActivity designer a button and a textView3
Upvotes: 1
Views: 49
Reputation: 49
onClick(View view)
and paste it directly in onCreate(Bundle savedInstance)
.Upvotes: 2