How to call method from another class in Android? - android

I've been trying to call a method from another class.
I have 2 classes. Timer.class and DecisionMaking.class. The Timer class is suppose to call a method (I just used a toast for now) from DecisionMaking.class once the timer is onFinish(). There is no error in my codes but when the timer finish counting, the method was not called and the emulator ask to Force Close. Both of the classes are in the same package. Is there anything that I'm missing?
Timer.class
public class Timer extends Activity{
TextView timeDisplay;
MyCount timer;
int length = 10000;
long startTime;
long timeRemaining;
DecisionMaking decisionmaking;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
timeDisplay = (TextView) findViewById(R.id.timer);
timer = new MyCount(length, 1000);
timer.start();
}
public class MyCount extends CountDownTimer {
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
public void onFinish() {
DecisionMaking decisionmaking = new DecisionMaking();
decisionmaking.sendSms();
timer.start();
}
public void onTick(long millisUntilFinished) {
timeDisplay.setText("Time:" + millisUntilFinished / 1000);
}
}
}
DecisionMaking.class
public class DecisionMaking extends Timer{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sendSms();
}
public boolean sendSms() {
Calendar cal = Calendar.getInstance();
Date d = cal.getTime();
int hour = d.getHours();
if (hour > 0 && hour < 6)
return false;
else
{
//Call SMS class here, remove toast
Toast.makeText(getBaseContext(), "SMS sent.", Toast.LENGTH_SHORT).show();
return true;
}
}
}

i think no need to call timer.start in the onFinish() method.

Related

Passing Countdown Timer beetwen Activities in Android

I'm trying to pass the a CountDownTimer value from Activity 1(PrimerNivel) to Activity 2(SegundoNivel)and start the CountDownTimer in Activity 2 from the value that got from the Activity 1.
But the CountDownTimer in Activity 2 is reset to zero. I can't find the error. could someone help me?
This is the code
Activity 1:
public class PrimerNivel extends InicioActivity {
private TextView cuentaRegresiva;
long startTime = 60 * 1000;
private final long interval = 1 * 1000;
MyCountDownTimer countDownTimer;
long tiempoRestante;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.juego);
cuentaRegresiva=(TextView)findViewById(R.id.cuentaRegresiva);
countDownTimer = new MyCountDownTimer(startTime, interval);
cuentaRegresiva.setText(cuentaRegresiva.getText() + String.valueOf(startTime / 1000));
}
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
cuentaRegresiva.setText("");
}
#Override
public void onTick(long millisUntilFinished) {
tiempoRestante= millisUntilFinished;
cuentaRegresiva.setText(""+millisUntilFinished/1000);
}}
OnClickListener siguiente =new OnClickListener(){
public void onClick(View arg0) {
Intent aNivelSiguiente = new Intent(PrimerNivel.this, SegundoNivel.class);
aNivelSiguiente.putExtra("regresivaAnterior", tiempoRestante);
startActivity(aNivelSiguiente);
PrimerNivel.this.finish();
}};
}
Activity 2:
public class SegundoNivel extends InicioActivity {
private TextView cuentaRegresiva;
long startTime;
private final long interval = 1 * 1000;
MyCountDownTimer countDownTimer;
Bundle bundle;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.juego);
cuentaRegresiva=(TextView)findViewById(R.id.cuentaRegresiva);
countDownTimer = new MyCountDownTimer(startTime, interval);
bundle = getIntent().getExtras();
startTime= bundle.getLong("regresivaAnterior")/1000;
cuentaRegresiva.setText(""+startTime);
countDownTimer.start();
}
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
cuentaRegresiva.setText("");
}
#Override
public void onTick(long millisUntilFinished) {
cuentaRegresiva.setText(""+millisUntilFinished/1000);
}}
You are creating the CountDownTimer before getting the value. Simply move the code that creates the timer to below where you get the value.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.juego);
cuentaRegresiva=(TextView)findViewById(R.id.cuentaRegresiva);
bundle = getIntent().getExtras();
startTime= bundle.getLong("regresivaAnterior")/1000;
// move it here after you've gotten the value
countDownTimer = new MyCountDownTimer(startTime, interval);
cuentaRegresiva.setText(""+startTime);
countDownTimer.start();
You may need to cancel your first timer to get the correct value at the correct time. Try calling
countDownTimer.cancel();
countDownTimer = null;
before creating the Intent. Also, you are dividing the startTime by 1000 after you get the value from the Intent. I'm not sure you want to be doing that.

how to get value from countdowntimer and display into toast

i have countdown timer from 1 to 9999 if i click start button the count will start, but if click stop button i need to get current value from countdown and display that value in toast but the countdown could not stop if i click stop button please help me
private CountDownTimer countDownTimer;
private boolean timerHasStarted = false;
private Button startB;
public TextView ;
private final long startTime = 9999 * 1;
private final long interval = 1 *1 ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startB = (Button) this.findViewById(R.id.button);
startB.setOnClickListener(this);
text = (TextView) this.findViewById(R.id.timer);
countDownTimer = new MyCountDownTimer(startTime, interval);
text.setText(text.getText() + String.valueOf(startTime / 1));
}
public void onClick(View v) {
if (!timerHasStarted) {
countDownTimer.start();
timerHasStarted = true;
startB.setText("STOP");
} else {
/*countDownTimer.cancel();
timerHasStarted = false;
startB.setText("RESTART");*/
}
}
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
//text.setText("Time's up!");
countDownTimer.start();
}
#Override
public void onTick(long millisUntilFinished) {
text.setText("" + millisUntilFinished / 1);
}
}
thank you
Here is my countdown timer:
QuestionCountdownTimer
public class QuestionCountdownTimer extends CountDownTimer {
private TextView remainingTimeDisplay;
private Context context;
public QuestionCountdownTimer(Context context,long millisInFuture, long countDownInterval,TextView remainingTimeDisplay) {
super(millisInFuture, countDownInterval);
this.context = context;
this.remainingTimeDisplay = remainingTimeDisplay;
}
#Override
public void onTick(long millisUntilFinished) {
long millis = millisUntilFinished;
String hms = String.format("%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
remainingTimeDisplay.setText(hms);
}
#Override
public void onFinish() {
Toast.makeText(context,"COUNTDOWN FINISH :)",Toast.LENGTH_SHORT).show();
}
}
Note:
TextView remainingTimeDisplay
remainingTimeDisplay.setText(hms);
I use it to display the remaining time using a TextView
Here I call the timer:
//Start Quiz timer
QuestionCountdownTimer timer = new QuestionCountdownTimer(this,10000, 1000, remainingTimeDisplay);
timer.start();
-first parameter: this - I use it for context to show Toast message
-second parameter: 10000 - total time (10 sec)
-third parameter: 1000 - countdown interval (1 sec)
-last parameter: dispaly remaining time in real time
Tested and working
Create your CountDownTimer like this:
public class MyCountDownTimer extends CountDownTimer
{
private long timePassed = 0;
public MyCountDownTimer(long startTime, long interval)
{
super(startTime, interval);
}
#Override
public void onFinish()
{
//text.setText("Time's up!");
countDownTimer.start();
}
#Override
public void onTick(long millisUntilFinished)
{
timePassed++;
text.setText("" + millisUntilFinished / 1);
}
public long getTimePassed()
{
return timePassed;
}
}
And on your onClick just do:
((MyCoundDownTimer) countDownTimer).getTimePassed();
to retrieve the time and set your textview text to it.
You should use handler
private Handler tickResponseHandler = new Handler() {
public void handleMessage(Message msg) {
int time = msg.what;
//make toast or do what you want
}
}
and pass it to MyCountDownTimer constructor
private Handler handler;
public MyCountDownTimer(long startTime, long interval, Handler handler) {
super(startTime, interval);
this.handler = handler;
}
And send message
#Override
public void onTick(long millisUntilFinished) {
text.setText("" + millisUntilFinished / 1);
Message msg = new Message();
msg.what = millisUntilFinished/1;
handler.sendMessage(msg);
}
That's all you need to do :)

How to display a timer in activity in Android

I want to show timer, with every second. After 20 seconds I want that activity to call itself.
But when I don't display the timer it waits for 20 seconds as I wish to do but as soon as I implement code to display timer it just starts and suddenly stops suddenly.
Here is my code. Please help me out.
public class MainActivity extends Activity {
public int time=20;
Button end;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread timerdisp = new Thread(){
TextView tv = (TextView) findViewById(R.id.timer);
public void run(){
try{
sleep(1000); // sleep for 1 seconds
tv.setText(String.valueOf(time));
time-=1;
if(time==0){
startActivity(new Intent(MainActivity.this,MainActivity.class));
}
run();
}
catch (InterruptedException e){
e.printStackTrace();
}
}
};
timerdisp.start();
);
}
Android provides a better facility of CountDownTimer, may be you should use that. As it provides many inbuilt methods and runs on background thread by default.
You can use onFinish() method to execute your call to the activity.
Here is an example of the same.
Try Below Code:
private long ms=0;
private long splashTime=2000;
private boolean splashActive = true;
private boolean paused=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Hides the titlebar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.splash);
Thread mythread = new Thread() {
public void run() {
try {
while (splashActive && ms < splashTime) {
if(!paused)
ms=ms+100;
sleep(100);
}
} catch(Exception e) {}
finally {
Intent intent = new Intent(Splash.this, Home.class);
startActivity(intent);
}
}
};
mythread.start();
}
and you can try this also
public class MainActivity extends Activity {
private CountDownTimer countDownTimer;
public TextView text;
private final long startTime = 20 * 1000;
private final long interval = 1 * 1000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.textView1);
countDownTimer = new MyCountDownTimer(startTime, interval);
text.setText(String.valueOf(startTime / 1000));
countDownTimer.start();
}
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
Intent intent = new Intent();
intent.setClass(getApplicationContext(),xxxx.class);
startActivity(intent);
}
#Override
public void onTick(long millisUntilFinished) {
text.setText("" + millisUntilFinished / 1000);
}
}
}
Use runOnUiThread
This acts as a normal Thread and will not allow your UI to sleep.
and the system will not hang.
or you can also use AsyncTask. I will prefer you using AsyncTask.
Use below code to call the function for every 20 seconds.
private Timer timer;
TimerTask refresher;
timer = new Timer();
refresher = new TimerTask() {
public void run() {
// your code to call every 20 seconds.
};
};
// first event immediately, following after 20 seconds each
timer.scheduleAtFixedRate(refresher, 0,1000*20);
Use below lines to show the time :
package com.example.test;
public class MainActivity extends Activity {
private Long startTime;
public native String getLastShotName();
public native String colorNormal();
public native String flipImage();
public native String forceInvertColor();
public native String getLastTitle();
public native String myMethod();
boolean mbFlip = false;
private Timer timer;
private Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TimerTask refresher;
startTime = System.currentTimeMillis();
handler.removeCallbacks(updateTimer);
handler.postDelayed(updateTimer, 1000);
}
#Override
protected void onResume() {
super.onResume();
handler.postDelayed(updateTimer, 1000);
}
private Runnable updateTimer = new Runnable() {
public void run() {
final TextView time = (TextView) findViewById(R.id.textView1);
Long spentTime = System.currentTimeMillis() - startTime;
Long minius = (spentTime/1000)/60;
Long seconds = (spentTime/1000) % 60;
time.setText(minius+":"+seconds);
handler.postDelayed(this, 1000);
}
};
}

How to add and remove time on CountDownTimer?

The question is: How can I add or remove time from the CountDownTimer during the count down?
For example: The user does something good: +5sec, the user does something wrong: -5sec.
Can someone help me with some code?
Maybe something like this
abstract class MyTimer {
public MyTimer(long deadline, long interval)
{
mDeadline = deadline;
mInterval = interval;
mTimer = new MyCountDownTimer(mDeadline, mInterval);
}
public synchronized void start() {
mTimer.start();
}
public abstract void onTick(long time);
public abstract void onFinish();
public synchronized void userDidRight()
{
mTimer.cancel();
mTimer = new MyCountDownTimer(mDeadline, mInterval += 5000);
mTimer.start();
}
public synchronized void userDidWrong()
{
mTimer.cancel();
mTimer = new MyCountDownTimer(mDeadline, mInterfval -= 5000);
mTimer.start();
}
private class MyCountDownTimer extends CountDownTimer() {
private abstract void onFinish() {
MyTimer.this.onFinish();
}
private abstract void onTick(long time) {
MyTimer.this.onTick(time);
}
}
private MyCountDownTimer mTimer;
}
You could restart the timer every time the user changes:
class Timer {
private long remainingTime;
private CoundDownTimer timer;
public void addTime(long addedTimeInMillis) {
createNewTimer(remainingTime + addedTimeInMills);
}
public void createNewTimer(long timeInMillis) {
if(timer != null) {
timer.cancel();
}
timer = new CountDownTimer(timeInMillis, 1000) {
#Override
public void onTick(final long millisUntilFinished) {
remainingTime = millisUntilFinished;
}
#Override
public void onFinish() {
// do something here
}
}.start();
}
}
private class startTimer extends CountDownTimer
{
public startTimer(long millisInFuture, long countDownInterval)
{
super(millisInFuture, countDownInterval);
}
#Override
public void onTick(long millisUntilFinished) {
currenttime=millisUntilFinished;
textview.setText("" + currenttime / 1000);
}
#Override
public void onFinish() {
textview.setText("done");
}
}
The above class is a simple derived class of CountDownTimer
CountDownTimer timer = new CountDownTimer(30000,1000);
timer.start();
long currentTime;
For example the above timer starts from 30 secs,decreases by one for each second.
To increase or decrease the timer dynamically you can cancel the old timer and initialize with your new time as shown below
timer.cancel();
timer = new CountDownTimer(currentTime+5000,1000);// +5000 to increase by 5 secs
timer.start();
you can make timer,currentTime variables as global then you can use the two different parts of code at different location.

How to start an activity upon the completion of a timer?

I'm trying to start a new activity "SMS.java", if I dont respond to my timer within 30secs. After 30secs, the new ativity should be started. Can anyone help me out??? The class Timer on line 5 extends a CountDownTimer..
Here's the code:
//TimerAct.java
public class TimerAct extends Activity
{
static TextView timeDisplay;
Timer t;
int length = 30000;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.time);
timeDisplay = (TextView) findViewById(R.id.timer);
timeDisplay.setText("Time left: " + length / 1000);
t = new Timer(length, 1000);
t.start();
View b1 = findViewById(R.id.abort);
b1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
t.cancel();
finish();
}
});
}
}
//Timer.java
public class Timer extends CountDownTimer
{
public Timer(long millisInFuture, long countDownInterval)
{
super(millisInFuture, countDownInterval);
}
public void onTick(long millisUntilFinished)
{
TimerAct.timeDisplay.setText("Time left: " + millisUntilFinished / 1000);
}
public void onFinish()
{
TimerAct.timeDisplay.setText("Time over!!!");
}
}
For a timer method, better you can use with threading. It will work.
This is the example for Show Timer in android using threads. It runs the thread every second. Change the time if you want.
Timer MyTimer=new Timer();
MyTimer.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
TimerBtn=(Button) findViewById(R.id.Timer);
TimerBtn.setText(new Date().toString());
}
});
}
}, 0, 1000);
What I do is call a method from the Activity on my CountDownTimer class, like this:
//Timer Class inside my Activity
public class Splash extends CountDownTimer{
public Splash(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
nextActivity(Login.class, true);
}
#Override
public void onTick(long millisUntilFinished) {}
}
//Method on my Activity Class
protected void nextActivity(Class<?> myClass, boolean finish) {
Intent myIntent = new Intent(this, myClass);
myIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(myIntent);
if(finish)
finish();
}

Categories

Resources