How can I increase my counter i here:
private void startTimer() {
int i = 0;
final Timer timer = new Timer();
final TimerTask task = new TimerTask() {
#Override
public void run() {
if(preferences.getBoolean(IS_RUNNING_KEY, false))
{
final int k = i++; //i must declared final error
runOnUiThread(new Runnable() {
#Override
public void run() {
timeCounter.setText(""+k);
Log.d("DTAG","K: "+k);
}
});
} else {
timer.cancel();
timer.purge();
}
}
};
timer.schedule(task, 1000);
}
You have to move i out of the scope of the function. Then it does not have to be declared final and you can change it. Change your code to this
private int i = 0;
private void startTimer() {
final Timer timer = new Timer();
final TimerTask task = new TimerTask() {
#Override
public void run() {
if(preferences.getBoolean(IS_RUNNING_KEY, false))
{
final int k = i++;
runOnUiThread(new Runnable() {
#Override
public void run() {
timeCounter.setText(""+k);
Log.d("DTAG","K: "+k);
}
});
} else {
timer.cancel();
timer.purge();
}
}
};
timer.schedule(task, 1000);
}
Related
I'm a newer programmer and this is my first project but I'm having a bit of trouble in making a proper loop with three timers that are supposed to run one after the other. I managed to get the objects to hold the values they are supposed to within the loop but for some reason, the timer isn't displaying in the text field like it should.
startBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("mTimer:", String.valueOf(mTimer));
Log.i("mReps:", String.valueOf(mReps));
Log.i("Flexion:", String.valueOf(flexionTimer));
Log.i("Hold:", String.valueOf(holdTimer));
Log.i("Extension:", String.valueOf(extensionTimer));
for (int iter = 0; iter < mReps; iter++) {
Log.i("Loop:", String.valueOf(iter));
final Timer workingFlexionTimer = new Timer();
workingFlexionTimer.schedule(new TimerTask() {
int counter = ((int) flexionTimer / 1000);
#Override
public void run () {
runOnUiThread(new Runnable() {
#Override
public void run() {
mPhase.setText("Flexion");
mCountDownTimer.setText("" + String.format(String.valueOf(counter + 1)));
}
});
if (counter-- == 0) {
workingFlexionTimer.cancel();
}
}
}, 0, 1000);
final Timer workingHoldTimer = new Timer();
workingHoldTimer.schedule(new TimerTask() {
int counter = ((int) holdTimer / 1000);
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
mPhase.setText("Hold!!!");
mCountDownTimer.setText("" + String.format(String.valueOf(counter + 1)));
}
});
if (counter-- == 0) {
workingHoldTimer.cancel();
}
}
}, flexionTimer, 1000);
final Timer workingExtensionTimer = new Timer();
workingExtensionTimer.schedule(new TimerTask() {
int counter = ((int) extensionTimer / 1000);
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
mPhase.setText("Extension");
mCountDownTimer.setText("" + String.format(String.valueOf(counter + 1)));
}
});
if (counter-- == 0) {
workingExtensionTimer.cancel();
}
}
}, (flexionTimer + holdTimer), 1000);
}
I'm kind of at a loss at this point and any suggestion would be appreciated.
Use handler
private void Timer() {
handler = new Handler();
Run =new Runnable() {
#Override
public void run() { //Do something after 10 sec
Toast.makeText(getActivity(), "Timer called!",Toast.LENGTH_LONG).show();
Timer(); // Do again
}};
handler.postDelayed(Run , 10000); // 10 sec
}
UPDATE
For timers I always do:
final TextView textView = (TextView)findViewById(R.id.textView);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
int counter = 10;
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText(""+counter);
}
});
if (counter-- == 0){
timer.cancel();
}
}
}, 0, 1000);
timer.schedule(new TimerTask() {
int counter = 10;
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText(""+counter);
}
});
if (counter-- == 0){
timer.cancel();
}
}
}, 10000, 1000);
timer.schedule(new TimerTask() {
int counter = 10;
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText(""+counter);
}
});
if (counter-- == 0){
timer.cancel();
}
}
}, 20000, 1000);
For more info check this
In the link...
public void schedule(TimerTask task, long delay, long period)
The above code. Start the run() without delay.
long delay = 0;// in ms
long period = 1000;// in ms
So every 1000ms call the run() and counter--. When counter = 0 cancel.
If you want to run, the one after the other, put delay.
UPDATE
Now the first will run immediately, the second will wait 10000ms (10s) and will run, finaly the third will wait 20000ms (20s) and then run.
The first timer flexionCountDownTimer was started in a loop, which means it will be started more than one time if mReps is greater than 1. This might leads to 2nd run of flexionCountDownTimer before the 1st run finished. Is this your expected behavior?
I would like to update the progressBar with Handler and for loop but without success.
Code:
public void increase_splash_bar (int from, int to)
{
Handler handler1 = new Handler(Looper.getMainLooper());
for (progress_k = from; progress_k<=to ;progress_k++)
{
handler1.postDelayed(new Runnable()
{
#Override
public void run()
{
FrontLayout.update_splash_progress_bar(progress_k, 100);
}
}, 2000);
}
}
Question:
The progress bar increase immediately to the end value instead of progressively.
Why?
Try this:
public void increase_splash_bar (int from, int to)
{
Handler handler1 = new Handler(Looper.getMainLooper());
for (progress_k = from; progress_k<=to ;progress_k++)
{
final int curr_progress_k = progress_k;
handler1.postDelayed(new Runnable()
{
#Override
public void run()
{
FrontLayout.update_splash_progress_bar(curr_progress_k, 100);
}
}, progress_k * 100); // adjust "100" value to adjust speed
}
}
Repeat a task with a time delay?
#inazaruk
private ProgressBar progressBar;
private Handler mHandler;
private int progressInt = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
progressBar = (ProgressBar) findViewById(R.id.pb);
progressBar.setProgress(0);
mHandler = new Handler();
runnable.run();
}
Runnable runnable = new Runnable() {
#Override
public void run() {
try {
updateProgress();
} catch (Exception ignored) {
} finally {
mHandler.postDelayed(runnable, progressInt);
}
}
};
private void updateProgress() {
progressInt += 1;
if (progressInt > 100) {
mHandler.removeCallbacks(runnable);
} else {
progressBar.setProgress(progressInt);
}
}
try this code:
Solution 1
public void increase_splash_bar (int from, int to)
{
Handler handler1 = new Handler();
class Task implements Runnable {
int start,end;
Task(int a,int b) { start = a; end = b;}
#Override
public void run() {
for (int i =start ; i <= end; i++) {
final int value = i;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler1.post(new Runnable() {
#Override
public void run() {
progressBar.setProgress(value);
}
});
}
}
}
Thread t = new Thread(new Task(from, to)); //call it
t.start();
}
Solution 2: More Simple
If thread is too much to ask for this problem..
you can use the following solution to use a single Handler to update progressbar:
code
public class HandlerDemo extends Activity
{
ProgressBar bar;
Handler handler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
bar.incrementProgressBy(5);
}
};
boolean isRunning = false;
#Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.main);
bar = (ProgressBar) findViewById(R.id.progress);
}
public void onStart()
{
super.onStart();
bar.setProgress(0);
Thread background = new Thread(new Runnable()
{
public void run()
{
try
{
for (int i = 0; i < 20 && isRunning; i++)
{
Thread.sleep(1000);
handler.sendMessage(handler.obtainMessage());
}
}
catch (Throwable t)
{
// just end the background thread
}
}
});
isRunning = true;
background.start();
}
public void onStop()
{
super.onStop();
isRunning = false;
}
}
Hope it helps..
Hi my app needs a realtime data from database and I'm posting it on my TextView and I can't update the TextView as the database updates. I tried using Timer but its still the same.
Here is my code,
public void startTimer() {
//set a new Timer
timer = new Timer();
//initialize the TimerTask's job
initializeTimerTask();
timer.schedule(timerTask, 0, 5000);
}
private void stopTimerTask() {
//stop the timer, if it's not already null
if (timer != null) {
timer.cancel();
timer = null;
}
}
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
final AcceptCars Cars = (AcceptCars) getIntent().getSerializableExtra("cars");
renterLat.setText(Cars.renterLat);
renterLng.setText(Cars.renterLng);
Log.d(TAG,renterLat.getText().toString());
Log.d(TAG,renterLng.getText().toString());
}
});
}
};
}
And here is where I get the Cars.renterLat and Cars.renterLng,
public class AcceptCars implements Serializable {
#SerializedName("renterLat")
public String renterLat;
#SerializedName("renterLng")
public String renterLng;
}
This is the logic you should be following. I used a Handler instead of a Timer. Inside the run method you need to call your webservice and get the updated value from the db. Use runOnUiThread to update the value to the UI from a Thread.
See the code below,
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Handler taskHandler = new Handler();
taskHandler.postDelayed(myTask, 0);
}
private Runnable myTask = new Runnable(){
public void run() {
queryDb();
// repeat the task
taskHandler.postDelayed(this, 1000);
}
};
private void queryDb(){
new Thread(new Runnable() {
#Override
public void run() {
// call you webservice
String data = callWebservice();
// parse the data in to AcceptCars pojo class
AcceptCars Cars = parseData(data);
//update the UI
runOnUiThread(new Runnable() {
#Override
public void run() {
renterLat.setText(Cars.renterLat);
renterLng.setText(Cars.renterLng);
}
});
}
}).start();
}
You can even use countdown timer.
Here is the link https://developer.android.com/reference/android/os/CountDownTimer.html
TimerTasks are really hard to deal with IMO. You should use a Handler and call postDelayed to do something after a certain amount of time.
Alternatively, you can try out this timer class I wrote:
import android.os.Handler;
public class Timer {
private Handler handler;
private boolean paused;
private int interval;
private Runnable task = new Runnable () {
#Override
public void run() {
if (!paused) {
runnable.run ();
Timer.this.handler.postDelayed (this, interval);
}
}
};
private Runnable runnable;
public int getInterval() {
return interval;
}
public void setInterval(int interval) {
this.interval = interval;
}
public void startTimer () {
paused = false;
handler.postDelayed (task, interval);
}
public void stopTimer () {
paused = true;
}
public Timer (Runnable runnable, int interval, boolean started) {
handler = new Handler ();
this.runnable = runnable;
this.interval = interval;
if (started)
startTimer ();
}
}
It is really simple to use.
You can use it like this:
Timer timer = new Timer(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
final AcceptCars Cars = (AcceptCars) getIntent().getSerializableExtra("cars");
renterLat.setText(Cars.renterLat);
renterLng.setText(Cars.renterLng);
Log.d(TAG,renterLat.getText().toString());
Log.d(TAG,renterLng.getText().toString());
}
}
}
}, 5000, true);
I am new to android development. I am making an app based on dictation.
In the activity below I have 15 small audio clips; the files play one after the other with a delay of 5 seconds.
My question is how can I play only 10 clips from the 15; also I want the 10 clips to be randomly played.
Any help will be appreciated.
package com.example.dictationary;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
public class Level1 extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.level1);
MediaPlayer n1 = MediaPlayer.create(this,R.raw.assassin);
final MediaPlayer n2 = MediaPlayer.create(this,R.raw.accessible);
final MediaPlayer n3 = MediaPlayer.create(this,R.raw.bashfully);
final MediaPlayer n4 = MediaPlayer.create(this,R.raw.blistering);
final MediaPlayer n5 = MediaPlayer.create(this,R.raw.butter);
final MediaPlayer n6 = MediaPlayer.create(this,R.raw.campaign);
final MediaPlayer n7 = MediaPlayer.create(this,R.raw.circumstances);
final MediaPlayer n8 = MediaPlayer.create(this,R.raw.clinching);
final MediaPlayer n9 = MediaPlayer.create(this,R.raw.deferential);
final MediaPlayer n10 = MediaPlayer.create(this,R.raw.distinguished);
final MediaPlayer n11 = MediaPlayer.create(this,R.raw.embarrass);
final MediaPlayer n12 = MediaPlayer.create(this,R.raw.etiquette);
final MediaPlayer n13 = MediaPlayer.create(this,R.raw.fatigue);
final MediaPlayer n14 = MediaPlayer.create(this,R.raw.feasible);
final MediaPlayer n15 = MediaPlayer.create(this,R.raw.glitch);
n1.start();
Timer buttonTimer = new Timer();
buttonTimer.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
n2.start();
}
});
}
}, 5000);
Timer buttonTimer1 = new Timer();
buttonTimer1.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
n3.start();
}
});
}
}, 10000);
Timer buttonTimer2 = new Timer();
buttonTimer2.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
n4.start();
}
});
}
}, 15000);
Timer buttonTimer3 = new Timer();
buttonTimer3.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
n5.start();
}
});
}
}, 20000);
Timer buttonTimer4 = new Timer();
buttonTimer4.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
n6.start();
}
});
}
}, 25000);
Timer buttonTimer5 = new Timer();
buttonTimer5.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
n7.start();
}
});
}
}, 30000);
Timer buttonTimer6 = new Timer();
buttonTimer6.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
n8.start();
}
});
}
}, 35000);
Timer buttonTimer7 = new Timer();
buttonTimer7.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
n9.start();
}
});
}
}, 40000);
Timer buttonTimer8 = new Timer();
buttonTimer8.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
n10.start();
}
});
}
}, 45000);
Timer buttonTimer9 = new Timer();
buttonTimer9.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
n11.start();
}
});
}
}, 50000);
Timer buttonTimer10 = new Timer();
buttonTimer10.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
n12.start();
}
});
}
}, 55000);
Timer buttonTimer11 = new Timer();
buttonTimer11.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
n13.start();
}
});
}
}, 60000);
Timer buttonTimer12 = new Timer();
buttonTimer12.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
n14.start();
}
});
}
}, 65000);
Timer buttonTimer13 = new Timer();
buttonTimer13.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
n15.start();
}
});
}
}, 70000);
}
}
You can put them in an array or list and access them with Random. Example:
Creating an ArrayList:
//Here we create the ArrayList
LinkedList<MediaPlayer> list = new LinkedList<MediaPlayer>(15);
list.add(new MediaPlayer .... // for each element.
Acess this sperated
// now we create the random int
Random r = new Random();
int pointer = r.nextInt(list.size());
// and here we access the "random" MediaPlayer
list.remove(pointer).start(); // gets a random media
where nextInt returns a value between 0 and <=list.size
// edit changed code
You cannot with the way your code is now organized...
You should refactor to
`MediaPlayer n = new MediaPlayer[];
n[1] = MediaPlayer.create(this,R.raw.assassin);
//...
n[15] = MediaPlayer.create(this,R.raw.assassin);
and then just pick a random number in interval [0-15) (15 excluded) and play that one.
Furthermore, your code would simplify alot, because only one recurring TimerTask is needed, and every time it would invoke a random number (word). However, this would introduce repeated words - to ensure no word is repeated, add the randomly picked number to a alreadyHeard list, and instead of playing that index simply pick a new one and test it again (in fact, while() pick them until you come up with one that isn't in the alreadyHeard list)
That should get you what you want :)
Trying to use a Timer to do run this 4 times with intervals of 10 seconds each.
I have tried stopping it with a loop, but it keeps crashing. Have tried using the schedule() with three parameters, but I didn't know where to implement a counter variable. Any ideas?
final Handler handler = new Handler();
Timer timer2 = new Timer();
TimerTask testing = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
Toast.makeText(MainActivity.this, "test",
Toast.LENGTH_SHORT).show();
}
});
}
};
int DELAY = 10000;
for (int i = 0; i != 2 ;i++) {
timer2.schedule(testing, DELAY);
timer2.cancel();
timer2.purge();
}
private final static int DELAY = 10000;
private final Handler handler = new Handler();
private final Timer timer = new Timer();
private final TimerTask task = new TimerTask() {
private int counter = 0;
public void run() {
handler.post(new Runnable() {
public void run() {
Toast.makeText(MainActivity.this, "test", Toast.LENGTH_SHORT).show();
}
});
if(++counter == 4) {
timer.cancel();
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timer.schedule(task, DELAY, DELAY);
}
Why not use an AsyncTask and just have it Thread.sleep(10000) and the publishProgress in a while loop? Here is what it would look like:
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
int i = 0;
while(i < 4) {
Thread.sleep(10000);
//Publish because onProgressUpdate runs on the UIThread
publishProgress();
i++;
}
// TODO Auto-generated method stub
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
//This is run on the UIThread and will actually Toast... Or update a View if you need it to!
Toast.makeText(MainActivity.this, "test", Toast.LENGTH_SHORT).show();
}
}.execute();
Also as a side note, for longer term repetitive tasks, consider using AlarmManager...
for(int i = 0 ;i<4 ; i++){
Runnable runnableforadd ;
Handler handlerforadd ;
handlerforadd = new Handler();
runnableforadd = new Runnable() {
#Override
public void run() {
//Your Code Here
handlerforadd.postDelayed(runnableforadd, 10000); }
};
handlerforadd.postDelayed(runnableforadd, i);
}