Intent with Countdown crashes android app - android

My Android app crashes when it reaches countdown 0. Below is the part of code related to it.
final CountDownTimer countdown=new CountDownTimer(60000, 1000){
public void onTick(long millisUntilFinished)
{
tvTime.setText((millisUntilFinished / 1000)+"'s");
}
public void onFinish()
{
try{
tvTime.setText("Time Over");
this.cancel();
Toast.makeText(getApplicationContext(),"Answer: "+ OriginalWord, Toast.LENGTH_LONG).show();
Intent i=new Intent(LastJumble.this,ScoreCard.class);
i.putExtra("username",username);
i.putExtra("totalQues", totalQues);
i.putExtra("count", count);
startActivity(i);
}
catch (Exception e) {
// TODO: handle exception
}
}
}.start();

this.cancel() will try to cancel the CountDownTimer. Since the timer is finished this will break. If you mean to call a cancel method in your outer class you should reference it as OuterClass.this.cancel() where OuterClass is the name of the class.

Related

How to implement timer based on current time in android

I want to implement a timer in my application if user click clock in button timer should start from device time and the timer should run when giving pause timer should pause when user click stop timer should stop, Please help me.
for example, now time is 13:20:10 user click means timer should run on this time not from 00, normal timer code I have, but based on the current time it should run.
you can try this. call start()/stop() when you want to start/stop timer. if you want to update UI (Main)Thread use runOnUiThread(https://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable)) or handler for update UI Thread
import java.util.Calendar;
int hou=0;
int min=0;
int sec=0;
boolean stopTimer=false;
private void initTimer()
{
Date currentTime = Calendar.getInstance().getTime();
hou=currentTime.getHours();
min=currentTime.getMinutes();
sec=currentTime.getSeconds();
Log.e("Initial Timer ","hou"+hou+ " min"+min+" sec"+sec);
startTimerThread();
}
private void startTimerThread()
{
new Thread()
{
public void run()
{
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
updateTimer();
}
}.start();
}
private void updateTimer()
{
if(!stopTimer)
{
sec=(((++sec)%60)==0)?0:sec;
min=(sec==0)?(((++min)%60==0)?0:min):min;
hou=(min==0)?((++hou)):hou;
/*hou%=12;*/
Log.e("Update Timer ","hou"+hou+ " min"+min+" sec"+sec);
startTimerThread();
}
}
public void start()
{
initTimer();
}
public void stop()
{
stopTimer=false;
}
you can try this using by using countdowntimer like this :
CountDownTimer timer = new CountDownTimer(1000000000, 1000) {
public void onTick(long millisUntilFinished) {
Calendar c = Calendar.getInstance();
Log.v(TAG , "CountDownTimer : " + c.get(Calendar.HOUR)+":"+c.get(Calendar.MINUTE)+":"+c.get(Calendar.SECOND));
}
public void onFinish() {
}
};
timer.start();
on pause you can cancel it like this:
timer.cancel();
i have take three button, first start button click on device time show in textview and it update as per device time. when click on paused button stop time update. and when click on restart time device time when start to stop.
mBtnStartTime?.setOnClickListener {
val someHandler = Handler(mainLooper)
someHandler.postDelayed(object : Runnable {
override fun run() {
mTvTime?.text = SimpleDateFormat("HH:mm:ss", Locale.US).format(Date())
someHandler.postDelayed(this, 1000)
}
}, 10)
mBtnPaused?.setOnClickListener {
someHandler.removeCallbacksAndMessages(null)
}
mBtnRestart?.setOnClickListener {
someHandler.postDelayed(object : Runnable {
override fun run() {
mTvTime?.text = SimpleDateFormat("HH:mm:ss", Locale.US).format(Date())
someHandler.postDelayed(this, 1000)
}
}, 10)
}

button.setText() and Thread.sleep()

Noob question on its way. In the code below I update text of a button in Android. Then I want to wait two seconds and then update the text again. If I comment the second b.setText("Send data"), the one after the sleep - then b.setText("Success") is written to the button. If I do not comment that one I will never see text "Success" on the button, only "Send data". It's like the Thread.sleep() is skipped when I have the second b.setText("Send data"). Google suggested to add a timer after setText("Success") so that setText() code would have time to be execited before the sleep. Did not help.
final Button b = (Button) findViewById(R.id.button);
b.setText("Send data");
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
b.setClickable(false);
b.setText("Success");
System.out.println("Debug before");
try
{
Thread.sleep(2000);
}
catch (Exception e)
{
}
System.out.println("Debug after");
b.setText("Send data");
b.setClickable(true);
}
});
Don't block your main thread. Use Handler.post instead
b.setClickable(false);
b.setText("Success");
System.out.println("Debug before");
new Handler().postDelayed(new Runnable(){
System.out.println("Debug after");
b.setText("Send data");
b.setClickable(true);
}, 2000);
There are many ways to do it.
you can run a new thread and then update view.
Or :
CountDownTimer countDownTimer = new CountDownTimer(2000, 1000) {
public void onTick(long millisUntilFinished) {
//
}
public void onFinish() {
//update your view
System.out.println("Debug after");
b.setText("Send data");
}
};
countDownTimer.start();

Want to use saveEventually() if save() not successful in Android

I need to save an object in parse. I want to use save() with timeout . If save() is not successful then it should use saveEventually(). Can I instead use saveEventually() with a timer if the timer expires before getting the callback from saveEventually() it should show a message.
userQuestions = new ParseObject("UserQuestions");
userQuestions.put("questionAsked", edt_askQuestion.getText().toString());
userQuestions.put("askedByUser", SignInActivity.pUser);
userQuestions.saveEventually(new SaveCallback() {
#Override
public void done(ParseException e) {
//cancel the timeout timer
countDownTimer.cancel();
Intent intent = new Intent(AActivity.this, DActivity.class);
intent.putExtra(Constants.Extras.INTENT_EXTRA_QUESTION, edt_askQuestion.getText().toString());
startActivity(intent);
}
});
//countdown timer for timeout
countDownTimer = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
LogUtil.d("seconds remaining: ", String.valueOf(millisUntilFinished / 1000));
}
public void onFinish() {
//if timer is triggered before saving object
Toast.makeText(AActivity.this, "Problem with net connectivity question will be saved when net is connected", Toast.LENGTH_SHORT).show();
}
}.start();
is this correct or is there any other way?

Trying to get a CountDownTimer to restart after 15 seconds.

I'm doing an app that displays various yoga poses for 60 seconds. I've been pulling my hair out trying to get a countdown timer to work the way I want. I need the timer to be able to pause, and restart automatically after 15 seconds. The CountDownTimer from Android didn't work because it had no pause. I tried 2 different versions of rewritten Android CountDownTimers and the classic version (Android CountDownTimer) and they all seem to have the same bug because they are using Handlers.
I've tried this version: http://www.java2s.com/Open-Source/Android/Timer/multitimer-android/com/cycleindex/multitimer/CountDownTimerWithPause.java.htm
I've tried this version: Android: CountDownTimer skips last onTick()! - I added an onFinish method to it.
I'm trying to do a Thread.sleep in the onFinish method for 15 seconds, and it is not updating the UI past the last second before moving into the Thread.sleep mode. In the following code, the TextView isn't getting updated to be set to empty string until after the Thread.sleep call.
cdt = new CountDownTimerWithPause(60000,1000,true) {
#Override
public void onTick(long millisUntiFinished) {
tvClock.setText("Remaining:" + millisUntiFinished/1000);
}
#Override
public void onFinish() {
tvClock.setText("");
bell.start();
if (bAutoPlayIsOn) {
tvClock.setText("waiting for next pose...");
try {
//15 second pauses between poses
Thread.sleep(15000);
//start over
listener.onForwardItemSelected();
ResetClocktoMaxTime(60000);
resume();
} catch (InterruptedException e) {
Log.d("Sleep Interrupted", e.toString());
e.printStackTrace();
}
catch (Exception e) {
Log.d("Timer", e.toString());
}
}
else {
tvClock.setText("Done");
btnStart.setText("Start ");
bClockIsTicking = false;
btnStart.setCompoundDrawablesWithIntrinsicBounds(null, playBtn, null, null);
}
}
};
Anyone have any ideas how to do this (restart after 15 seconds) differently?
The onFinish method is being called from the interface thread, so any interface changes you make won't actually redraw until onFinish returns. Try something like this:
cdt = new CountDownTimerWithPause(60000,1000,true) {
#Override
public void onTick(long millisUntiFinished) {
tvClock.setText("Remaining:" + millisUntiFinished/1000);
}
#Override
public void onFinish() {
tvClock.setText("");
bell.start();
if (bAutoPlayIsOn) {
tvClock.setText("waiting for next pose...");
(
new Thread() {
public void run() {
try {
//15 second pauses between poses
Thread.sleep(15000);
getActivity().runOnUiThread
(
new Runnable() {
public void run() {
//start over
listener.onForwardItemSelected();
ResetClocktoMaxTime(60000);
resume();
}
}
);
}
catch (InterruptedException e) {
Log.d("Sleep Interrupted", e.toString());
e.printStackTrace();
}
catch (Exception e) {
Log.d("Timer", e.toString());
}
}
}
).start();
}
else {
tvClock.setText("Done");
btnStart.setText("Start ");
bClockIsTicking = false;
btnStart.setCompoundDrawablesWithIntrinsicBounds(null, playBtn, null, null);
}
}
};

Android timer with do while

My code is crashing and I need some help. Everything is running fine except for this part.
There is no errors but it crashes at timer.schedule(loadImg2, 5000); that is before the if (!c.moveToNext())
My question: am I using the timer correctly in the loop? Because that is where the code crashes.
I never see this log "+-+-+-+-+-+-+-+-+- Getting out " or anything that comes after.
do
{
Log.v("log_tag", "+-+-+-+-+-+-+-+-+- Ttrying to cancel ");
//timer.cancel();
Log.v("log_tag", "+-+-+-+-+-+-+-+-+- Timer canceled ");
timer = new Timer();
Log.v("log_tag", "+-+-+-+-+-+-+-+-+- New timer created ");
//delay amount of time(5s here) in milliseconds before first execution.
//period amount of time(1s here) in milliseconds between subsequent executions.
timer.schedule(loadImg2, 5000); //this did not produce any effect so far
if (!c.moveToNext())
{
//destroy
timer.cancel();
myImageView.setImageBitmap(null);
Log.v("log_tag", "+-+-+-+-+-+-+-+-+- Getting out ");
//get out of the loop or set c.moveToFirst()
break;
}
} while (true);
TimerTask loadImg2 = new TimerTask()
{
#Override
//Load Img2
public void run()
{
runOnUiThread(new Runnable()
{
public void run()
{
Log.v("log_tag", "+-+-+-+-+-+-+-+-+- Inside loadImg2 ");
titleText.setText(DisplayTitle(c));
Bitmap bitmap2 = BitmapFactory.decodeFile(c.getString(5));
myImageView = (ImageView) findViewById(R.id.imageview1);
myImageView.setImageBitmap(null);
timer.cancel();
}
});
}
}
There is a problem that you can't set timer.schedule() more than once time.
Try to catch an exception:
try{
timer.schedule(loadImg2, 5000);
} catch (IllegalArgumentException e){
Log.v(TAG, "IllegalArgumentException");
} catch (IllegalStateException e){
Log.v(TAG, "IllegalStateException");
}
Then the application doesn't crash. But the timer will set just in the first time.
I don't know the solution of this problem. I am trying to find it too.

Categories

Resources