I am displaying text in textview that changes after a period of time.I want to do this on a loop ie the text reverts to its original and then changes again.Here is the code.
MainActivity.java
qoutes=(TextView)rootView.findViewById(R.id.textView_q);
Handler handler = new Handler();
handler.postDelayed(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
qoutes.setText("I don’t trust words. I trust pictures. – Gilles Peress ");
}
}, 10000);
Handler handler1 = new Handler();
handler.postDelayed(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
qoutes.setText("You don’t take a photograph. You ask quietly to borrow it. – Unknown ");
}
}, 20000);
Try this.
qoutes=(TextView)rootView.findViewById(R.id.textView_q);
int i = 0;
Handler handler = new Handler();
handler.postDelayed(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
if(i%2==0){
qoutes.setText("I don’t trust words. I trust pictures. – Gilles Peress ");
}else{
qoutes.setText("You don’t take a photograph. You ask quietly to borrow it. – Unknown ");
}
i++;
}
}, 10000);
Edit:
Timer timer;
TimerTask timertask;
int i = 0;
qoutes=(TextView)rootView.findViewById(R.id.textView_q);
timer = new Timer();
timertask = new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if(i%2==0){
qoutes.setText("I don’t trust words. I trust pictures. – Gilles Peress ");
}else{
qoutes.setText("You don’t take a photograph. You ask quietly to borrow it. – Unknown ");
}
i++;
}
});
}
};
timer.scheduleAtFixedRate(timertask, 100, 10000);
First, create your String resources and a member variable to keep track of the current text shown. It would be best to store in strings.xml, but for this simple example we'll just use a String array. Also create a Handler as a member variable.
TextView qoutes;
Handler handler = new Handler();
int currentTextPosition = -1;
String[] textArray = new String[]{"I don’t trust words. I trust pictures. – Gilles Peress ",
"You don’t take a photograph. You ask quietly to borrow it. – Unknown "};
Then, in onCreateView():
qoutes=(TextView)rootView.findViewById(R.id.textView_q);
handler.postDelayed(setTextRunnable, 10000);
And, the definition for your Runnable:
Runnable setTextRunnable = new Runnable(){
#Override
public void run() {
if (currentTextPosition < 0 ) {
currentTextPosition = 0;
} else {
currentTextPosition++;
if (currentTextPosition >= textArray.length) {
currentTextPosition = 0;
}
}
qoutes.setText(textArray[currentTextPosition]);
handler.postDelayed(this, 10000);
}
};
This will run every 10 seconds until you stop it, which you can do by calling:
handler.removeCallbacks(setTextRunnable);
Related
I'm working on React Native and i want to create a never ending service that run every (n) seconds on Native Modules (on this topic is android).
I've create a simple service like this
public void startTimer() {
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
Log.v(TAG, "SERVICE RUN");
try{
if(haveNetworkConnection()){
db.openDB();
if(db.countRowNewStructure()>0){
//send data to server
} else{
Log.v(TAG, "No data should be send to server");
}
} else {
Log.v(TAG, "Ga ada sinyal");
}
} catch (JSONException e){
e.printStackTrace();
}
}
}, 0, 1000);
}
above code run every second to check, but i'm facing the problem when i re-run the service from React Native, the log showing me those code every 0.5 seconds
the simulation may be like :
0----------------1 //seconds
startTimer()
re-run startTimer() conscious
0----------------1 //seconds
startTimer()
//now i have two startTimer() that will run every 1 sec on different interval
I want to keep my startTimer() just running once even I trigger startService() every 0.5 sec.
how can i do that? is it possible?
this may help you. Timmer to perform the certain action in android after the particular time.
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask timertaskforsynctime = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
#Override
public void run() {
// your action here
}
});
}
};
timer.schedule(timertaskforsynctime,5000,10000);// decide the time when it will start and after how much time it will run continusly.
}`
for one time
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
// your code that will run after 1 sec
}
}, 1000);
You could make use of the cancel method to cancel the previous Timer.
public class YourModule extends ReactContextBaseJavaModule {
Timer tim = new Timer();
public void startTimer() {
tim.cancel();
tim = new Timer();
tim.scheduleAtFixedRate(
new TimerTask() {
public void run() {
// Run tasks
}
},
0,
1000);
}
}
my_text.setText("Dave");
//Small pause...
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
my_text.setText("Bob");
I want to change my textView, pause 1 second, then change it again. When I run the program, it doesn't refresh after first change. It just shows the second change after returning. How can I force the refresh on the first change to the textview?
Try use Handler like below code
my_text.setText("Dave");
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
my_text.setText("Bob");
}
});
}
}, 1000);
Try below for the edited question
Keep your all 20 names in any collection array or list.
int position = 0;
String names [] = {"0","1","20"};
Handler handler = new Handler(getMainLooper());
Runnable runnable = new Runnable() {
public void run() {
my_text.setText(names[position++]);
if (position < names.length) {
handler.postDelayed(this, 1000);
}
}
};
handler.postDelayed(runnable, 1000);
I need a delay for around 5 seconds. I have tried using Timer using below code :
Timer myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
Log.d(TAG,"Timer");
}
}, 4000, 5000);
When i check logs, the Timer is getting printed thrice. If I change time, sometimes it gets printed in log 4 times as well.
I have tried using Handler as well like below :
final Handler mHandler = new Handler();
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
Thread.sleep(10000);
mHandler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Log.d(Utility.TAG,"Sleep::");
}
});
} catch (Exception e) {
// TODO: handle exception
}
}
}
}).start();
But again the log is printing multiple times. I just want to call my method once not multiple times. How can I achieve it ?
EDIT
used handler without thread as well like below :
final Handler h = new Handler();
final int delay = 3000; //milliseconds
h.postDelayed(new Runnable(){
public void run(){
//do something
h.postDelayed(this, delay);
Log.d(Utility.TAG,"Sleep ::");
}
}, delay);
But again, Log is getting printed thrice
Your third approach (no Timer, no Thread) is the closest to being correct. It's printing multiple times because the Runnable is re-posting itself every time it runs. If you only want it to run once, remove this line from the run() method:
h.postDelayed(this, delay);
I am using a toast for Count Down Timer, so the toast should change it's text in every second. I use this to display the toast for exactly 1 second but i want the toast to repeat itself. Hope i make you understand.
toast = Toast.makeText(getApplicationContext(), text.getText().toString(), Toast.LENGTH_SHORT); toast.show();
Handler handler = new Handler();
handler.postDelayed
(new Runnable() {
#Override
public void run() {
toast.cancel();
}
}, 1000);
This will show a new toast every second for exactly one second.
int count = 100; //Declare as inatance variable
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
final Toast toast = Toast.makeText(
getApplicationContext(), --count + "",
Toast.LENGTH_SHORT);
toast.show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
toast.cancel();
}
}, 1000);
}
});
}
}, 0, 1000);
run() is called after every second. so show toast there.
Handler handler = new Handler();
handler.postDelayed
(new Runnable() {
#Override
public void run() {
toast.cancel();
toast = Toast.makeText(getApplicationContext(), text.getText().toString(),Toast.LENGTH_SHORT);
toast.show();
}
}, 1000);
This page describes a way to keep the toast be shown indefinitely. So when you have the text view of the toast on hand, you may change the text as you like.
you have to learn more about android srvices
create java class extends from IntentService
override this function
#Override
protected void onHandleIntent(Intent intent) {
try {
Toast.makeText(context,"Click on Location button to find your bus !",Toast.LENGTH_LONG).show();
Thread.sleep(5000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
go to manifest an type
go to your launcher java class and
Intent intent = new Intent(this, Service_toast.class);
startService(intent);
====>> for more information about services vist android devloper :
https://developer.android.com/guide/components/services.html
I am scheduling a simple task that should update a text field in 4 seconds.
However everytime this is called the activity pauses and does not show the value in the text field until I restart the activity.
private void showDelayedValue() {
Runnable longRunningTask = new Runnable() {
public void run() {
int randomVal = randomNumberGenerator.nextInt(30 - -10) - 10; //random number between -10 and 30
String randomValStr = Integer.toString(randomVal);
Log.i(this.getClass().getSimpleName(),
"FIRED startScheduler: " + randomValStr);
theFieldOnScreenTV.setText(randomTempStr);
}
};
//show the value in 2 seconds
scheduledTaskExecutor.schedule(longRunningTask, 4, TimeUnit.SECONDS);
}
The log shows:
FIRED startScheduler: 4
but does not update the TextView theFieldOnScreenTV
Instead onPause is called right after Fired startScheduler: is displayed in LogCat.
Many thanks!
EDIT:
This worked for me following Alex' approach:
private void showDelayedValue() {
int randomX = randomNumberGenerator.nextInt(30 - -10) - 10;
final String randomXStr = Integer.toString(randomX);
final Runnable updateFieldR = new Runnable() {
public void run() {
theFieldOnScreenTV.setText(randomXStr);
}
};
Runnable longRunningTask = new Runnable() {
public void run() {
theFieldOnScreenTV.post(updateFieldR);
}
};
scheduledTaskExecutor.schedule(longRunningTask, 4, TimeUnit.SECONDS);
}
instead of
theFieldOnScreenTV.setText(randomTempStr);
try
theFieldOnScreenTV.post(new Runnable() { theFieldOnScreenTV.setText(randomTempStr); } );
Have a try using Handlers.
Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
theFieldOnScreenTV.setText(randomTempStr);
}
});