In my app i have Countdown Timer and dialog box in same class. when someone press quit button dialog box opens and in it 2 buttons yes and no. I want when someone press quit button timer pause and if someone press no button its resume with remaining seconds. I know for this i have to finish this timer and create new timer with remaining seconds. But i am unable to get remaining seconds. If someone know how to do this please help me.
Code of countdown timer-
counterTimer = new CountDownTimer(15000, 1000) {
public void onFinish() {
if(currentGame.getRound()==20)
{
nextBtn1.setEnabled(false);
nextBtn2.setEnabled(false);
nextBtn3.setEnabled(false);
nextBtn4.setEnabled(false);
nextBtn5.setEnabled(false);
final Handler handle = new Handler();
Toast.makeText(QuestionActivity.this, "Time's Up", Toast.LENGTH_SHORT).show();
Runnable delay = new Runnable() {
public void run() {
System.exit(0);
}
};
handle.postDelayed(delay,3000);
}
else if(currentGame.getRound()==0)
{
currentGame.decrementScore();
final Handler handle = new Handler();
Runnable delay = new Runnable() {
public void run() {
processScreen();
}
};
handle.postDelayed(delay,3000);
}
else if(currentGame.getRound()<=19)
{
nextBtn1.setEnabled(false);
nextBtn2.setEnabled(false);
nextBtn3.setEnabled(false);
nextBtn4.setEnabled(false);
nextBtn5.setEnabled(false);
currentGame.decrementScore();
final Handler handle = new Handler();
Toast.makeText(QuestionActivity.this, "Time's Up", Toast.LENGTH_SHORT).show();
Runnable delay = new Runnable() {
public void run() {
processScreen();
}
};
handle.postDelayed(delay,3000);
}
}
public void onTick(long millisUntilFinished) {
TextView time = (TextView) findViewById(R.id.timers);
time.setText( ""+millisUntilFinished/1000);
}
};
counterTimer.start();
}
Code for Dialog Box-
if(arg0.getId()==R.id.quit)
{
Button yes, no;
final Dialog dialog = new Dialog(this, R.style.FullHeightDialog);
dialog.setContentView(R.layout.dialog1);
dialog.setCancelable(true);
counterTimer.cancel();
//to set the message
TextView message =(TextView) dialog.findViewById(R.id.tvmessagedialogtext);
message.setText("Are you sure you want to Exit?");
yes = (Button) dialog.findViewById(R.id.bmessageDialogYes);
yes.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
finish();
startActivity(new Intent(QuestionActivity.this, SplashActivity.class));
}
});
no = (Button) dialog.findViewById(R.id.bmessageDialogNo);
no.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
dialog.dismiss();
nextBtn1.setEnabled(true);
nextBtn2.setEnabled(true);
nextBtn3.setEnabled(true);
nextBtn4.setEnabled(true);
}
});
dialog.show();
}
Dialog Box Code-
private long remaingtime, starttime = 15000;
MyCounter timer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.question);
nextBtn1 = (Button) findViewById(R.id.answer1);
nextBtn1.setEnabled(true);
nextBtn1.setOnClickListener(this);
nextBtn2 = (Button) findViewById(R.id.answer2);
nextBtn2.setEnabled(true);
nextBtn2.setOnClickListener(this);
nextBtn3 = (Button) findViewById(R.id.answer3);
nextBtn3.setEnabled(true);
nextBtn3.setOnClickListener(this);
nextBtn4 = (Button) findViewById(R.id.answer4);
nextBtn4.setEnabled(true);
nextBtn4.setOnClickListener(this);
nextBtn5 = (Button) findViewById(R.id.quit);
nextBtn5.setEnabled(true);
nextBtn5.setOnClickListener(this);
timer = new MyCounter(starttime, 1000);
timer.start();
}
if(arg0.getId() == R.id.quit)
{
timer.cancel();
final Dialog dialog = new Dialog(this, R.style.FullHeightDialog);
dialog.setContentView(R.layout.dialog1);
dialog.setCancelable(true);
//to set the message
TextView message =(TextView) dialog.findViewById(R.id.tvmessagedialogtext);
message.setText("Are you sure you want to Exit?");
yes = (Button) dialog.findViewById(R.id.bmessageDialogYes);
yes.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
startActivity(new Intent(QuestionActivity.this, SplashActivity.class));
finish();
}
});
no = (Button) dialog.findViewById(R.id.bmessageDialogNo);
no.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
dialog.dismiss();
timer = new MyCounter(remaingtime, 1000);
timer.start();
nextBtn1.setEnabled(true);
nextBtn2.setEnabled(true);
nextBtn3.setEnabled(true);
nextBtn4.setEnabled(true);
}
});
dialog.show();
}
Count Down Timer Code-
public class MyCounter extends CountDownTimer
{
public MyCounter(long millisInFuture, long countDownInterval)
{
super(millisInFuture, countDownInterval);
}
#Override
public void onTick(long millisUntilFinished)
{
remaingtime = millisUntilFinished;
time = (TextView) findViewById(R.id.timers);
time.setText(""+millisUntilFinished/1000);
}
#Override
public void onFinish()
{
if(currentGame.getRound()==20)
{
nextBtn1.setEnabled(false);
nextBtn2.setEnabled(false);
nextBtn3.setEnabled(false);
nextBtn4.setEnabled(false);
nextBtn5.setEnabled(false);
final Handler handle = new Handler();
Toast.makeText(QuestionActivity.this, "Time's Up", Toast.LENGTH_SHORT).show();
Runnable delay = new Runnable() {
public void run() {
System.exit(0);
}
};
handle.postDelayed(delay,3000);
}
else if(currentGame.getRound()==0)
{
currentGame.decrementScore();
final Handler handle = new Handler();
Runnable delay = new Runnable() {
public void run() {
processScreen();
}
};
handle.postDelayed(delay,3000);
}
else if(currentGame.getRound()<=19)
{
nextBtn1.setEnabled(false);
nextBtn2.setEnabled(false);
nextBtn3.setEnabled(false);
nextBtn4.setEnabled(false);
nextBtn5.setEnabled(false);
currentGame.decrementScore();
final Handler handle = new Handler();
Toast.makeText(QuestionActivity.this, "Time's Up", Toast.LENGTH_SHORT).show();
Runnable delay = new Runnable() {
public void run()
{
processScreen();
}
};
handle.postDelayed(delay,3000);
}
}
}
Just count the seconds yourself on each tick and use them later to create a new timer.
try like that
private final long interval = 1000;
long millisLeft = 90000;
public class MalibuCountDownTimer extends CountDownTimer {
public MalibuCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
Toast.makeText(context, "Time's up!", Toast.LENGTH_LONG).show();
}
#Override
public void onTick(long millisUntilFinished) {
millisLeft = millisUntilFinished;
System.out.println("The milies left is" + millisLeft);
}
}
#Override
public void onResume() {
super.onResume();
countDownTimer = new MalibuCountDownTimer(millisLeft, interval);
countDownTimer.start();
}
public void onPause() {
super.onPause();
countDownTimer.cancel();
}
Related
I am using SweetAlert Dialog for android.
https://github.com/pedant/sweet-alert-dialog
In the success dialog, I want to remove to the OK Button since I am using timer option, however no option for doing so has been mentioned in their docs. Please explain how can I remove the OK button.
MainActivity.java
public class Main2Activity extends AppCompatActivity {
private Firebase mRootRef;
private Button mBtn1;
private Button mBtn2;
int counter;
int counter1;
long value;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Firebase.setAndroidContext(this);
mBtn1 = (Button) findViewById(R.id.btn1);
mBtn2 = (Button) findViewById(R.id.btn2);
mBtn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v.equals(mBtn1)) {
mRootRef = new Firebase("https://voting-cf0fa.firebaseio.com/House/Jupiter/Player 1");
final Firebase mRefChild = mRootRef.child("Votes");
mRefChild.runTransaction(new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(final MutableData currentData) {
if (currentData.getValue() == null) {
currentData.setValue(1);
} else {
currentData.setValue((Long) currentData.getValue() + 1);
}
return Transaction.success(currentData);
}
public void onComplete(FirebaseError firebaseError, boolean committed, DataSnapshot currentData) {
}
});
MediaPlayer click1 =MediaPlayer.create(getApplicationContext(), R.raw.click);
click1.start();
mBtn1.setEnabled(false);
mBtn2.setEnabled(false);
Timer buttonTimer = new Timer();
buttonTimer.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
mBtn1.setEnabled(true);
mBtn2.setEnabled(true);
}
});
}
}, 5000);
final SweetAlertDialog Voted = new SweetAlertDialog(Main2Activity.this, SweetAlertDialog.SUCCESS_TYPE);
Voted.setTitleText("Voted");
Voted.setContentText("You Have cast your Vote!");
Voted.show();
Voted.findViewById(R.id.confirm_button).setVisibility(View.GONE);
final Timer t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
Voted.dismiss();
t.cancel();
}
}, 5000);
}
}
});
mBtn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mRootRef = new Firebase("https://voting-cf0fa.firebaseio.com/House/Jupiter/Player 2");
if (v.equals(mBtn2)) {
Firebase mRefChild = mRootRef.child("Votes");
mRefChild.runTransaction(new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(final MutableData currentData) {
if (currentData.getValue() == null) {
currentData.setValue(1);
} else {
currentData.setValue((Long) currentData.getValue() + 1);
}
return Transaction.success(currentData);
}
public void onComplete(FirebaseError firebaseError, boolean committed, DataSnapshot currentData) {
}
});
MediaPlayer click2 =MediaPlayer.create(getApplicationContext(), R.raw.click);
click2.start();
mBtn2.setEnabled(false);
mBtn1.setEnabled(false);
Timer buttonTimer = new Timer();
buttonTimer.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
mBtn2.setEnabled(true);
mBtn1.setEnabled(true);
}
});
}
}, 5000);
final SweetAlertDialog Voted = new SweetAlertDialog(Main2Activity.this, SweetAlertDialog.SUCCESS_TYPE);
Voted.setTitleText("Voted");
Voted.setContentText("You Have cast your Vote!");
Voted.show();
Voted.findViewById(R.id.confirm_button).setVisibility(View.GONE);
final Timer t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
Voted.dismiss();
t.cancel();
}
}, 5000);
}
}
});
}
#Override
public void onBackPressed() { }
}
I am assuming your code is look like
new SweetAlertDialog(this, SweetAlertDialog.SUCCESS_TYPE)
.setTitleText("Good job!")
.setContentText("You clicked the button!")
.show();
So the answer is
SweetAlertDialog dialog = new SweetAlertDialog(this, SweetAlertDialog.SUCCESS_TYPE)
.setTitleText("Good job!")
.setContentText("You clicked the button!")
.show();
dialog.findViewById(R.id.confirm_button).setVisibility(View.GONE);
This also works
SweetAlertDialog sweetdialog = new SweetAlertDialog(this, SweetAlertDialog.SUCCESS_TYPE)
.setTitleText("Good job!")
.setContentText("You clicked the button!")
.show();
sweetdialog.getButton(SweetAlertDialog.BUTTON_CONFIRM).setVisibility(View.GONE);
new SweetAlertDialog(this, SweetAlertDialog.SUCCESS_TYPE)
.setTitleText("Good job!")
.setContentText("You clicked the button!")
.show();
// dont forget to add this in build.gradle
implementation 'com.github.f0ris.sweetalert:library:1.6.2'
I am creating a voting app. A Firebase database counts the number of clicks of a button and displays it. However on closing the app and restarting, the number of clicks start back from zero. How can I keep adding the number the votes to the child node even after the app is closed and restarted instead of starting the votes from zero?
mainactivity.java
public class Main2Activity extends AppCompatActivity {
private Firebase mRootRef;
private Button mBtn1;
private Button mBtn2;
int counter = 0;
int counter1 = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Firebase.setAndroidContext(this);
mBtn1 = (Button) findViewById(R.id.btn1);
mBtn2 = (Button) findViewById(R.id.btn2);
mBtn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v.equals(mBtn1)) {
mRootRef = new Firebase("https://voting-cf0fa.firebaseio.com/House/Jupiter/Player 1");
Firebase mRefChild = mRootRef.child("Votes");
counter++;
mRefChild.setValue(counter);
MediaPlayer click1 =MediaPlayer.create(getApplicationContext(), R.raw.click);
click1.start();
mBtn1.setEnabled(false);
mBtn2.setEnabled(false);
Timer buttonTimer = new Timer();
buttonTimer.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
mBtn1.setEnabled(true);
mBtn2.setEnabled(true);
}
});
}
}, 5000);
final AlertDialog.Builder Voted = new AlertDialog.Builder(Main2Activity.this);
Voted.setTitle("Voted");
Voted.setMessage("You have cast Your Vote!");
Voted.setCancelable(false);
final AlertDialog dlg = Voted.create();
dlg.show();
final Timer t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
dlg.dismiss();
t.cancel();
}
}, 5000);
}
}
});
mBtn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mRootRef = new Firebase("https://voting-cf0fa.firebaseio.com/House/Jupiter/Player 2");
if (v.equals(mBtn2)) {
Firebase mRefChild = mRootRef.child("Votes");
counter1++;
mRefChild.setValue(counter1);
MediaPlayer click2 =MediaPlayer.create(getApplicationContext(), R.raw.click);
click2.start();
mBtn2.setEnabled(false);
mBtn1.setEnabled(false);
Timer buttonTimer = new Timer();
buttonTimer.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
mBtn2.setEnabled(true);
mBtn1.setEnabled(true);
}
});
}
}, 5000);
final AlertDialog.Builder Voted = new AlertDialog.Builder(Main2Activity.this);
Voted.setTitle("Voted");
Voted.setMessage("You Have cast your Vote");
Voted.setCancelable(false);
final AlertDialog dlg = Voted.create();
dlg.show();
final Timer t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
dlg.dismiss();
t.cancel();
}
}, 5000);
}
}
});
}
#Override
public void onBackPressed() { }
}
From the Firebase documentation :
Use our transactions feature when working with complex data that could be corrupted by concurrent updates
public void incrementCounter() {
firebase.runTransaction(new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(final MutableData currentData) {
if (currentData.getValue() == null) {
currentData.setValue(1);
} else {
currentData.setValue((Long) currentData.getValue() + 1);
}
return Transaction.success(currentData);
}
#Override
public void onComplete(FirebaseError firebaseError, boolean committed, DataSnapshot currentData) {
if (firebaseError != null) {
Log.d("Firebase counter increment failed.");
} else {
Log.d("Firebase counter increment succeeded.");
}
}
});
}
I am developing an application in which I want to implement timer task to print a toast message every 5 seconds. The problem is my application crashes after 5 seconds when i run it.Below is part of my code please tell me where I am making mistakes and how can I overcome it.
public class main_activity extends Activity implements BluetoothLeUart.Callback{
public ImageButton fabbutton;
Activity activity;
Timer time;
TimerTask timetask;
Handler handle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity);
fabbutton = (ImageButton) findViewById(R.id.fabbutton);
startTimer(); //this is where I start my timer task
fabbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
scanLeDevice(false);
Intent intent = new Intent(getApplicationContext(), ScanList.class);
startActivity(intent);
}
});
}
public void startTimer(){
time = new Timer();
initializeTimerTask();
time.schedule(timetask, 5000, 10000);
}
public void initializeTimerTask(){
timetask = new TimerTask() {
#Override
public void run() {
handle.post(new Runnable() {
#Override
public void run() {
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(getApplicationContext(),"Timer...", duration);
toast.show();
}
});
}
};
}
public void stoptimertask() {
//stop the timer, if it's not already null
if (time != null) {
time.cancel();
time = null;
}
}
}
you forgot to initialize handler,
Just add below line in oncreate or startTimer();
handle = new Handler();
Or even in your case you can use,
runOnUiThread(new Runnable(){
#Override
public void run() {
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(getApplicationContext(),"Timer...", duration);
toast.show();
}
});
I want to do app to show 3 elements (each 2 seconds) and each start showing after the before element. Here is code:
public class Remember extends Activity
{
TextView text;
ImageView element1, element2, element3, element4 ,element5, element6;
Button button1, button2, button3, button4, button5, button6;
int data, id;
Random random;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_remember);
random = new Random();
id=1;
text = (TextView)findViewById(R.id.text);
element1 = (ImageView)findViewById(R.id.element1);
element2 = (ImageView)findViewById(R.id.element2);
element3 = (ImageView)findViewById(R.id.element3);
element4 = (ImageView)findViewById(R.id.element4);
element5 = (ImageView)findViewById(R.id.element5);
element6 = (ImageView)findViewById(R.id.element6);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
button4 = (Button) findViewById(R.id.button4);
button5 = (Button) findViewById(R.id.button5);
button6 = (Button) findViewById(R.id.button6);
element1.setVisibility(View.GONE);
element2.setVisibility(View.GONE);
element3.setVisibility(View.GONE);
element4.setVisibility(View.GONE);
element5.setVisibility(View.GONE);
element6.setVisibility(View.GONE);
data = random.nextInt(6)+1;
}
public void button1(View v)
{
gameStart();
}
public void gameStart()
{
do{
if (data==1)
{
CountDownTimer cdt = new CountDownTimer(2000, 1000)
{
#Override
public void onTick(long millisUntilFinished)
{
element1.setVisibility(View.VISIBLE);
}
#Override
public void onFinish()
{
element1.setVisibility(View.GONE);
}
}.start();
}
else if (data==2)
{
CountDownTimer cdt = new CountDownTimer(2000, 1000)
{
#Override
public void onTick(long millisUntilFinished)
{
element2.setVisibility(View.VISIBLE);
}
#Override
public void onFinish()
{
element2.setVisibility(View.GONE);
}
}.start();
}
else if (data==3)
{
CountDownTimer cdt = new CountDownTimer(2000, 1000)
{
#Override
public void onTick(long millisUntilFinished)
{
element3.setVisibility(View.VISIBLE);
}
#Override
public void onFinish()
{
element3.setVisibility(View.GONE);
}
}.start();
}
else if (data==4)
{
CountDownTimer cdt = new CountDownTimer(2000, 1000)
{
#Override
public void onTick(long millisUntilFinished)
{
element4.setVisibility(View.VISIBLE);
}
#Override
public void onFinish()
{
element4.setVisibility(View.GONE);
}
}.start();
}
else if (data==5)
{
CountDownTimer cdt = new CountDownTimer(2000, 1000)
{
#Override
public void onTick(long millisUntilFinished)
{
element5.setVisibility(View.VISIBLE);
}
#Override
public void onFinish()
{
element5.setVisibility(View.GONE);
}
}.start();
}
else if (data==6)
{
CountDownTimer cdt = new CountDownTimer(2000, 1000)
{
#Override
public void onTick(long millisUntilFinished)
{
element6.setVisibility(View.VISIBLE);
}
#Override
public void onFinish()
{
element6.setVisibility(View.GONE);
}
}.start();
}
id=id+1;
text.setText("cos " + id);
data = random.nextInt(6)+1;
try
{
Thread.sleep(2000);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}while(id<=3);
}
}
But if I clicked start application start lagging and everything go to norm after time which all elements should be hide. If I delete Thread.sleep all elements show in the same time. What should I do?
Thread.sleep(2000); on the ui thread blocks the ui thread. You should never block the ui thread. Remove the sleep.
To create a delay use a Handler.
Read
http://developer.android.com/guide/components/processes-and-threads.html
I'm trying to cancel the countdowntimer on onbackpressed, I put counter.cancel; there but "'count' cannot be resolved" error appears. I think It can't find the countdowntimer!
There is a btn_riazi1_1_1 that can cancel the timer.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_riazi1_1);
//// handling timer
final TextView textic = (TextView) findViewById(R.id.riazi1_1_timer);
final CountDownTimer Count = new CountDownTimer(5000, 1000) {
public void onTick(long millisUntilFinished) {
textic.setText(getResources().getString(R.string.remaintime) + millisUntilFinished / 1000);
}
public void onFinish() {
textic.setText(getResources().getString(R.string.timesup));
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i=new Intent(Riazi1_1.this,Riazi1_2.class);
startActivity(i);
}
}, 1000);
}
};
Count.start();
/////////////////
//// handling button1
Button btn1 = (Button) findViewById(R.id.btn_riazi1_1_1);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Count.cancel();
TextView txtwrong = (TextView) findViewById(R.id.txt_wrong_riazi1_1);
txtwrong.setVisibility(View.VISIBLE);
Button btn2 = (Button) findViewById(R.id.btn_riazi1_1_2);
btn2.setBackgroundColor(Color.GREEN);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i=new Intent(Riazi1_1.this,Riazi1_2.class);
startActivity(i);
}
}, 1000);
}
});
}
#Override
public void onBackPressed(){
super.onBackPressed();
Count.cancel(); // error: Count cannot be resolved ///
}
}
You have declared the TImer within onCreate method. So you cannot access it outside of onCreate. Declare it as a member variable.
private CountDownTimer Count; /// declare it as a member variable
and in the onCreate method initialize it like
Count = new CountDownTimer(5000, 1000).....
[A suggestion, use the naming convension. naming a variable starting with capital letter is really confusing]