The timer not let the user to edit - java

I'm a begginer and i build a timer app and i want the app to allow the user to edit the time. like in the android build in timer. and i wrote the code and it not really works it's show like it can be edit but when i'm trying to write something, it's change for a sec and go back to what it's been before..
xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_stopwatch"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.adir.stopwatch.StopwatchActivity"
android:background="#000000"
>
<Button
android:id="#+id/reset_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClickReset"
android:text="#string/reset"
android:textColor="#FFFFFF"
android:layout_below="#+id/stop_button"
android:layout_alignLeft="#+id/stop_button"
android:layout_alignStart="#+id/stop_button" />
<EditText
android:id="#+id/time_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="17dp"
android:text=""
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="92sp"
android:textColor="#FFFFFF"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:inputType="time"
/>
<Button
android:id="#+id/start_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClickStart"
android:text="#string/start"
android:textColor="#FFFFFF"
android:layout_below="#+id/time_view"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp" />
<Button
android:id="#+id/stop_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClickStop"
android:text="#string/stop"
android:textColor="#FFFFFF"
android:layout_alignLeft="#+id/start_button"
android:layout_alignStart="#+id/start_button"
android:layout_below="#+id/start_button"></Button>
</RelativeLayout>
Java:
public class StopwatchActivity extends Activity {
private int seconds=0;
private boolean running;
private boolean wasRunning;
public String time;
public int hours=seconds/3600;
public int minutes=(seconds%3600)/60;
public int secs=seconds%60;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stopwatch);
if(savedInstanceState!=null){
seconds=savedInstanceState.getInt("seconds");
running=savedInstanceState.getBoolean("running");
wasRunning=savedInstanceState.getBoolean("wasRunning");
}
runTimer();
}
public void onClickStart(View view) {
running = true;
}
protected void onStop(){
super.onStop();
wasRunning=running;
running=false;
}
protected void onStart() {
super.onStart();
if(wasRunning){
running=true;
}
}
public void onClickStop(View view) {
running = false;
}
public void onClickReset(View view) {
running = false;
seconds = 0;
}
private void runTimer() {
final EditText timeView = (EditText) findViewById(R.id.time_view);
time=timeView.getText().toString();
final Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
time = String.format("%d:%02d:%02d",hours, minutes, secs);
timeView.setText(time);
if (running) {
seconds--;
}
handler.postDelayed(this, 1000);
}
});
}
public void onSaveInstanceState(Bundle savedInstanceState){
savedInstanceState.putInt("seconds",seconds);
savedInstanceState.putBoolean("running",running);
savedInstanceState.putBoolean("wasRunning",wasRunning);
}
protected void onPause(){
super.onPause();
wasRunning=running;
running=false;
}
protected void onResume(){
super.onResume();
if(wasRunning){
running=true;
}
}
}
What do i need to fix?

The code below will give you a good idea of what to do. When you click the button, it will get the text of the EditText and put it into string. Then it will convert into int. Then you can put the new int variable time into your CountDownTimer function's 1st parameter to set the length of the timer.
Button submit;
TextView timerText;
EditText editTextTime;
CountdownTimer yourTimer;
String timeString;
int time;
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
timeString = String.valueOf(editTextTime.getText());
time = Integer.valueOf(timeString);
}
});
yourTimer = new CountDownTimer(time, 1000) {
#Override
public void onTick(long millisUntilFinished) {
int seconds = (int) millisUntilFinished / 1000;
int minutes = seconds / 60;
seconds %= 60;
minutes %= 60;
if (seconds < 10 && seconds >= 1) {
timerText.setText("" + seconds);
}
}
#Override
public void onFinish() {
}
}.start();

Related

How i can fix AsyncTask error with TextView [duplicate]

This question already has answers here:
android.content.res.Resources$NotFoundException: String resource ID #0x0
(8 answers)
Closed 3 years ago.
I want to display a timer from 1 to 100 in my TextView, but this throws me an Exception. My application throws a RuntimeException like shown below:
Thanks in advance for your help.
java.lang.RuntimeException: An error occurred while executing
doInBackground()
My MainActivity class where the RuntimeException is thrown.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView txt = findViewById(R.id.txt);
Button button1 = findViewById(R.id.bt1);
Button button2 = findViewById(R.id.bt2);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new QQ().execute();
}
});
}
public void onProgressUpdate(int i) {
TextView txt = findViewById(R.id.txt);
Button button1 = findViewById(R.id.bt1);
Button button2 = findViewById(R.id.bt2);
txt.setText(i);
}
private class QQ extends AsyncTask<Integer, Integer, Integer> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected Integer doInBackground(Integer... args) {
for (int i = 0; i < 1000000; i++) {
try {
Thread.sleep(1000); ///задержка
} catch (InterruptedException e) {
e.printStackTrace();
}
publishProgress(i);
return null;
}
return null;
}
private void publishProgress(int i) {
publishProgressq(i);
}
protected void onPostExecute(int i) {
}
}
private void publishProgressq(int i) {
onProgressUpdate(i);
}
}
My Layout class in xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#bbbbbb"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#bbbbbb"
android:gravity="top"
android:orientation="horizontal">
<TextView
android:id="#+id/txt"
android:layout_width="151dp"
android:layout_height="110dp"
android:textSize="45dp"
android:text="0">
</TextView>
<Button
android:id="#+id/bt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="START" />
<Button
android:id="#+id/bt2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="STOP" />
</LinearLayout>
</LinearLayout>
You can change your code as below:
public void onProgressUpdate(int i) {
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView txt = findViewById(R.id.txt);
Button button1 = findViewById(R.id.bt1);
Button button2 = findViewById(R.id.bt2);
txt.setText(i);
}
});
}
It will run on main thread.
Inside your public void onProgressUpdate , set text like this :
txt.setText(String.valueOf(i));
If you set a TextView to an int, it will be interpreted as an Android resource id. If you want the value of the int as your text (and not the resource it points to), make it a String first.

Splash Screen Android - Count Down Timer Display

I am trying to use splash screen for my app.
I want to display Count down timer in my splash screen.
So far I am able to achieve the splash screen working but don't know how to display count down timer. I created layout for count down timer. I want splash screen to stay for 5 Hours then take to the next activity.
Splashactivity.java
public class splash_screen extends AppCompatActivity {
private float imageAplha = 1f;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
//splashScreenUseTimer(5000);
splashScreenUseAsyncTask();
}
// Show splash screen until network load data complete.
private void splashScreenUseAsyncTask()
{
// Create a AsyncTask object.
final RetrieveDateTask retrieveDateTask = new RetrieveDateTask();
retrieveDateTask.execute("", "", "");
// Get splash image view object.
final ImageView splashImageView = (ImageView) findViewById(R.id.logo_id);
// Create a count down timer object.It will count down every 0.1 seconds and last for milliSeconds milliseconds..
CountDownTimer countDownTimer = new CountDownTimer(5000, 100) {
#Override
public void onTick(long l) {
// Reduce the splash screen background image's alpha value for each count down.
splashImageView.setAlpha(imageAplha);
imageAplha -= 0.1;
if(imageAplha <= 0)
{
imageAplha = 1;
}
}
#Override
public void onFinish() {
// When count down complete, set the image to invisible.
imageAplha = 0;
splashImageView.setAlpha(imageAplha);
// If AsyncTask is not complete, restart the counter to count again.
if(!retrieveDateTask.isAsyncTaskComplete()) {
this.start();
}
}
};
// Start the count down timer.
countDownTimer.start();
}
// This is the async task class that get data from network.
private class RetrieveDateTask extends AsyncTask<String, String, String>{
// Indicate whether AsyncTask complete or not.
private boolean asyncTaskComplete = false;
public boolean isAsyncTaskComplete() {
return asyncTaskComplete;
}
public void setAsyncTaskComplete(boolean asyncTaskComplete) {
this.asyncTaskComplete = asyncTaskComplete;
}
// This method will be called before AsyncTask run.
#Override
protected void onPreExecute() {
this.asyncTaskComplete = false;
}
// This method will be called when AsyncTask run.
#Override
protected String doInBackground(String... strings) {
try {
// Simulate a network operation which will last for 10 seconds.
Thread currTread = Thread.currentThread();
for (int i = 0; i < 10; i++) {
currTread.sleep(1000);
}
}catch(Exception ex)
{
ex.printStackTrace();
}finally {
return null;
}
}
// This method will be called after AsyncTask run.
#Override
protected void onPostExecute(String s) {
// Start SplashScreenMainActivity.
Intent mainIntent = new Intent(splash_screen.this,
MainActivity.class);
splash_screen.this.startActivity(mainIntent);
// Close SplashScreenActivity.
splash_screen.this.finish();
this.asyncTaskComplete = true;
}
}
}
Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0"
android:background="#color/White"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical">
<ImageView
android:id="#+id/logo_id"
android:layout_width="350dp"
android:layout_height="match_parent"
app:srcCompat="#drawable/ts_logo"
android:layout_gravity="center"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"
android:orientation="vertical">
<LinearLayout
android:id="#+id/linear_layout_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/black"
android:visibility="visible">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="#+id/tv_hour"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="00"
android:textColor="#android:color/white"
android:textSize="20dp"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_hour_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hour"
android:textColor="#android:color/white"
android:textSize="20dp"
android:textStyle="normal" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="#+id/tv_minute"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="00"
android:textColor="#android:color/white"
android:textSize="20dp"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_minute_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Minute"
android:textColor="#android:color/white"
android:textSize="20dp"
android:textStyle="normal" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="#+id/tv_second"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="00"
android:textColor="#android:color/white"
android:textSize="20dp"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_second_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Second"
android:textColor="#android:color/white"
android:textSize="20dp"
android:textStyle="normal" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</LinearLayout>
#contact dummy I edited #Dev code with small modification.try this one. Based on your animation requirement increase and decrease imageAlpha size.
private float imageAplha = 1f;
private boolean imageStatus = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
splashScreenUseAsyncTask();
}
// Show splash screen until network load data complete.
private void splashScreenUseAsyncTask()
{
// Create a AsyncTask object.
final RetrieveDateTask retrieveDateTask = new RetrieveDateTask();
retrieveDateTask.execute("", "", "");
// Get splash image view object.
final ImageView splashImageView = (ImageView) findViewById(R.id.logo_id);
final TextView tv_hour = (TextView) findViewById(R.id.tv_hour);
final TextView tv_minute = (TextView) findViewById(R.id.tv_minute);
final TextView tv_second = (TextView) findViewById(R.id.tv_second);
// Create a count down timer object.It will count down every 0.1 seconds and last for milliSeconds milliseconds..
final int time= 3600000*5;
CountDownTimer countDownTimer = new CountDownTimer(time, 1000) {
#Override
public void onTick(long l) {
long Days = l / (24 * 60 * 60 * 1000);
long Hours = l / (60 * 60 * 1000) % 24;
long Minutes = l / (60 * 1000) % 60;
long Seconds = l / 1000 % 60;
//
// tv_days.setText(String.format("%02d", Days));
tv_hour.setText(String.format("%02d", Hours));
tv_minute.setText(String.format("%02d", Minutes));
tv_second.setText(String.format("%02d", Seconds));
splashImageView.setAlpha(imageAplha);
if(imageStatus){
imageAplha += 1;
if(imageAplha >= 1)
{
// imageAplha-= 0.5;
imageStatus = false;
}
}else{
imageAplha -= 1;
if(imageAplha <= 0)
{
imageStatus = true;
}
}
}
#Override
public void onFinish() {
// When count down complete, set the image to invisible.
imageAplha = 0;
splashImageView.setAlpha(imageAplha);
// If AsyncTask is not complete, restart the counter to count again.
if(!retrieveDateTask.isAsyncTaskComplete()) {
this.start();
}
}
};
// Start the count down timer.
countDownTimer.start();
}
// This is the async task class that get data from network.
private class RetrieveDateTask extends AsyncTask<String, String, String> {
// Indicate whether AsyncTask complete or not.
private boolean asyncTaskComplete = false;
public boolean isAsyncTaskComplete() {
return asyncTaskComplete;
}
public void setAsyncTaskComplete(boolean asyncTaskComplete) {
this.asyncTaskComplete = asyncTaskComplete;
}
// This method will be called before AsyncTask run.
#Override
protected void onPreExecute() {
this.asyncTaskComplete = false;
}
// This method will be called when AsyncTask run.
#Override
protected String doInBackground(String... strings) {
try {
// Simulate a network operation which will last for 10 seconds.
Thread currTread = Thread.currentThread();
for (int i = 0; i < 18000000; i++) {
currTread.sleep(1000);
}
}catch(Exception ex)
{
ex.printStackTrace();
}finally {
return null;
}
}
// This method will be called after AsyncTask run.
#Override
protected void onPostExecute(String s) {
// Start SplashScreenMainActivity.
Intent mainIntent = new Intent(splash_screen .this,
MainActvity.class);
splash_screen.this.startActivity(mainIntent);
// Close SplashScreenActivity.
splash_screen.this.finish();
this.asyncTaskComplete = true;
}
}
}
#contact dummy I have edited your code try using this
// Show splash screen until network load data complete.
private void splashScreenUseAsyncTask()
{
// Create a AsyncTask object.
final RetrieveDateTask retrieveDateTask = new RetrieveDateTask();
retrieveDateTask.execute("", "", "");
// Get splash image view object.
final ImageView splashImageView = (ImageView) findViewById(R.id.logo_id);
//for 5 Hours
final int time= 3600000*5;
CountDownTimer countDownTimer = new CountDownTimer(time, 1000) {
#Override
public void onTick(long l) {
long Days = l / (24 * 60 * 60 * 1000);
long Hours = l / (60 * 60 * 1000) % 24;
long Minutes = l / (60 * 1000) % 60;
long Seconds = l / 1000 % 60;
//
tv_days.setText(String.format("%02d", Days));
tv_hour.setText(String.format("%02d", Hours));
tv_minute.setText(String.format("%02d", Minutes));
tv_second.setText(String.format("%02d", Seconds));
splashImageView.setAlpha(imageAplha);
imageAplha -= 0.1;
if(imageAplha <= 0)
{
imageAplha = 1;
}
}
#Override
public void onFinish() {
// When count down complete, set the image to invisible.
imageAplha = 0;
splashImageView.setAlpha(imageAplha);
// If AsyncTask is not complete, restart the counter to count again.
if(!retrieveDateTask.isAsyncTaskComplete()) {
this.start();
}
}
};
// Start the count down timer.
countDownTimer.start();
}

My app crashes after clicking button

When I click the button my app crashes and I have no idea why. I've looked up my code a lot of times but can't seem to find any "major flaws". The purpose of the app is just clicking the button twice as fast as possible and it displays the amount of time needed from the first tap to the second tap. Some sort of reaction thing. I used a timer because I didn't know what else to use.
(Value of start time) - (value of current timer) = (time between first and second click).
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"
tools:context="com.keklabs.reactiontimer.MainActivity">
<TextView
android:id="#+id/scoreText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="78dp"
android:text="Click below to start!"
android:textColor="#39FF14"
android:textSize="30dp" />
<Button
android:id="#+id/startStopButton"
android:layout_width="match_parent"
android:layout_height="350dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="#000000"
android:text="Start / Stop"
android:textSize="25dp"
android:textColor="#39FF14" />
</RelativeLayout>
public class MainActivity extends AppCompatActivity {
private final long startTime = 0;
private final long interval = 100;
private boolean buttonClicked;
private Button startStopButton;
private TextView scoreText;
CountDownTimer timer = new CountDownTimer(30000, 100) {
#Override
public void onTick(long millisUntilFinished) {
scoreText.setText("kek"); //displayed text is value of starttime (30000) - current value of timer,
} //some sort of reaction game thing
#Override
public void onFinish() {
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView scoreText = (TextView) findViewById(R.id.scoreText);
Button startStopButton = (Button) findViewById(R.id.startStopButton);
startStopButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!buttonClicked) {
timer.start();
buttonClicked = true;
}
else {
timer.cancel();
buttonClicked = false;
}
}
});
}
}
EDIT
How do i do it the right way in the line scoreText.setText(startTime - millisUntilFinished); to display startTime-current timer value?
CountDownTimer timer = new CountDownTimer(startTime, interval) {
#Override
public void onTick(long millisUntilFinished) {
scoreText.setText(startTime - millisUntilFinished);
}
#Override
public void onFinish() {
}
};
Actually, you are declaring your TextView scoreText twice. One gloabally and other locally. You can replace TextView scoreText = (TextView) findViewById(R.id.scoreText);
to scoreText = (TextView) findViewById(R.id.scoreText);
in your onCreate()

Handle Toggle States in onResume() using Intent and SharedPreferences

I have written a program in which i am using Timer and controlling that timer using Toggle states,
Like: My Toggle's default state is OFF, once i make changes in toggle state from OFF to ON TIMER starts, and when i again change to OFF it stops the timer as per requirement.
But problem starts when my Timer is ON and I switch to other activity and then again come back to Toggle activity and then do changes in toggle state from ON to OFF - it still runs Timer...
ToggleActivity.java:
public class ToggleActivity extends Activity implements OnCheckedChangeListener {
ToggleButton toggleButton;
TextView text;
Timer timer;
TimerTask timerTask;
final Handler handler = new Handler();
Button btnSwitchActivity;
boolean toggleState;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_toggle);
toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
text = (TextView) findViewById(R.id.textView1);
btnSwitchActivity = (Button) findViewById(R.id.btnSwitchActivity);
sharedPreferences = getApplicationContext().getSharedPreferences("toggleState",0);
toggleButton.setOnCheckedChangeListener(this);
btnSwitchActivity.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intentSwitchActivity = new Intent(ToggleActivity.this, SwitchActivity.class);
startActivity(intentSwitchActivity);
}
});
}
#Override
public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
if(isChecked)
{
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("toggleState", true);
editor.commit();
text.setText("ON");
startTimer();
} else
{
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("toggleState", false);
editor.commit();
text.setText("OFF");
if (timer != null) {
timer.cancel();
timer = null;
}
}
}
public void startTimer() {
timer = new Timer();
initializeTimerTask();
timer.schedule(timerTask, 1000, 5000);
}
public void stoptimertask(View v) {
if (timer != null) {
timer.cancel();
timer = null;
}
}
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
final String strDate = simpleDateFormat.format(calendar.getTime());
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(getApplicationContext(), strDate, duration);
toast.show();
}
});
}
};
}
public void onResume() {
super.onResume();
toggleState = sharedPreferences.getBoolean("toggleState", false);
Log.v("toggleState-onResume()", Boolean.toString(toggleState));
if (toggleState) {
toggleButton.setChecked(true);
} else {
toggleButton.setChecked(false);
}
}
}
SwitchActivity.java:
public class SwitchActivity extends Activity {
Button btnToggleActivity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_switch);
btnToggleActivity = (Button) findViewById(R.id.btnToggleActivity);
btnToggleActivity.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(SwitchActivity.this, ToggleActivity.class);
startActivity(intent);
/**
* if i use finish() instead of Intent to switch to ToggleActivity
* my Timer works fine
*/
// finish
}
});
}
}
activity_toggle.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:gravity="center"
android:background="#ffffff"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".ToggleActivity" >
<ToggleButton
android:id="#+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/toggle_selector"
android:checked="false"
android:text=""
android:textOff=""
android:textOn="" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp"
android:text="#string/string_toggle_off"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="#+id/btnSwitchActivity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/string_btn_switch"/>
</LinearLayout>
activity_switch.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:background="#ffffff"
android:orientation="vertical" >
<Button
android:id="#+id/btnToggleActivity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/string_btn_goback"
/>
</LinearLayout>
You should probably save the state of the toggle button in the savedInstanceState bundle by overriding onSaveInstanceState.
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outstate.putBoolean("KEY", yourButton.isToggle())
}
And then you can access it by reading the savedInstanceState bundle given to you in onCreate of your activity or onCreateView/onViewCreated if you work in a fragment.
Hope this helps.

How to use a button from my other class in a CountDownTimer | Beginner

I'm creating a Reaction time Test app, with one button. I create this button in my first Class: ReactionTestActivity. Now I want to use it in my CountDownTimer, but how do I do this?
public class CDT extends CountDownTimer {
public CDT (long millisInFuture, long countDownInterval, ReactionTestActivity RAT){
super(millisInFuture, countDownInterval);
}
public void onFinish(){
button.setText("press");
}
#Override
public void onTick(long millisUntilFinished) {
}
}
You just created the class. Assuming you're doing Android, you need to do the rest of Android stuff:
public class TimerActivity extends Activity implements OnClickListener {
private CountDownTimer countDownTimer;
private boolean timerHasStarted = false;
private Button startB;
public TextView text;
private final long startTime = 30 * 1000;
private final long interval = 1 * 1000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timer);
startB = (Button) this.findViewById(R.id.button);
startB.setOnClickListener(this);
text = (TextView) this.findViewById(R.id.timer);
//NOTE: I don't know what you expect as the third parameter
countDownTimer = new CDT(startTime, interval, null);
text.setText(text.getText() + String.valueOf(startTime/1000));
}
#Override
public void onClick(View v) {
if (!timerHasStarted) {
countDownTimer.start();
timerHasStarted = true;
startB.setText("STOP");
} else {
countDownTimer.cancel();
timerHasStarted = false;
startB.setText("RESTART");
}
}
public class CDT extends CountDownTimer {
//your class definition that you wrote above.
}
}
Now you need the XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#drawable/bgi" >
<TextView
android:id="#+id/timer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:paddingRight="10dip"
android:textSize="50dp" />
<Button
android:id="#+id/button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:text="Start" />
</RelativeLayout>
Source:
http://androidbite.blogspot.com/2012/11/android-count-down-timer-example.html

Categories