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);
Related
How I can set dynamically set the progressbar status after reading a value from db SQLite?
I have this code.
int i = 0;
while (!c.isAfterLast()) {
i++;
pb.setProgress(i)
}
But my problem is that progress bar is update only at finish while so without "liveEffect"
You can use runOnUiThread method of Activity class:
runOnUiThread(new Runnable() {
#Override
public void run() {
pb.setProgress(i);
}
});
More here: https://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable)
Actually, execution time is too low that by live effect not appear . take large cursor around 10000 value then apply loop now you can see progress
I resolved my problem with Handler and Thread.sleep (for simulate live)
new Thread(new Runnable() {
public void run() {
do {
mProgressStatus++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
mHandler.post(new Runnable() {
public void run() {
pb.setProgress(mProgressStatus);
}
);
} while (c.moveToNext());
}
}).start();
I am developing an app in which a thread will run in main thread and it will call a list of users in every 1 sec,but i am getting the pop up that ANR. please suggest. How To Resolve?
Below is my code
super.onCreate(savedInstanceState);
System.setProperty("java.net.preferIPv4Stack", "true");
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_main);
mHandler = new Handler();
Runnable runable = new Runnable() {
#Override
public void run() {
try{
listofUsers = GcmIntentService.getListOfUsers();
if (listofUsers.size() > 0) {
for (int index = 0; index < listofUsers.size(); index++) {
if (index == 0) {
startTime = listofUsers.get(0).getLoggedinDateTime();
} else {
Calendar calender1 = Calendar.getInstance();
calender1.setTime(startTime);
calender1.add(Calendar.SECOND, i);
newTime = calender1.getTime();
listofUsers.get(index).setLoggedinDateTime(newTime);
i = i + 72;
}
///user time is checked with the current system time.
Iterator<UserInformation> userDetailsIter = listofUsers.iterator();
Calendar calender2 = Calendar.getInstance();
while (userDetailsIter.hasNext()) {
UserInformation newUserInfo = userDetailsIter.next();
Date userTime=newUserInfo.getLoggedinDateTime();
Date systemTime=calender2.getTime();
if ( userTime.compareTo(systemTime) < 0 ) {
userDetailsIter.remove();
}
}
}
}
mHandler.postDelayed(this, 1000);
}
catch (Exception e) {
// TODO: handle exception
}
finally{
//also call the same runnable
mHandler.postDelayed(this, 100);
}
}
};
mHandler.postDelayed(runable, 100);
}
Please help me by guiding me about what I have done wrong
You can't make a while loop or any kind of long running operation on main queue
why don't you make a normal thread inside a repeated timer
like the below code
Timer myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
check();
}
}, 0, 100);
and inside check make a thread and do what ever you want
public void check(){
new Thread(new new Runnable() {
#Override
public void run() {
// do what you want here
}
}).start();
}
I want to present bitmap images from a internetstream. Every 500 millisec i get a new image and i want to present this image to the user. What is the best way to do this? Can i use an image view and chenge the image every 500 millisec?
I tried to do this in an timer task like this:
timer.schedule(new TimerTask() {
public void run() {
if(flag){
Bitmap bmp = null;
Log.i(APPID, "New frame");
try {
bmp = session.getImage();
setImage(bmp);
} catch (Exception e) {
e.printStackTrace();
}
} else {
timer.cancel();
}
}
}, 500, 500);
But this does not work.
Updating the UI from a thread other than the UI/main thread will fail as Android does not allow it. Try using a Handler to post messages back to the UI thread. You could do something like this.
final Handler h = new Handler();
timer.schedule(new TimerTask() {
public void run() {
if(flag){
h.post(new Runnable() {
public void run() {
Bitmap bmp = null;
Log.i(APPID, "New frame");
try {
bmp = session.getImage();
setImage(bmp);
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
timer.cancel();
}
}
}, 500, 500);
Timer task runs on a different thread. you need to update ui on the ui thread. You should use runOnUiThread or Handler
runOnUiThread(new Runnable() //run on ui threa
{
public void run()
{
// update ui here
}
});
Handler
Handler m_handler;
Runnable m_handlerTask ;
m_handler= new Handler();
m_handlerTask = new Runnable()
{
#Override
public void run() {
// do soemthing
m_handler.postDelayed(m_handlerTask, 1000);
// change 1000 to whatever you want
}
};
m_handlerTask.run();
When you wan to cancel call this m_handler.removeCallbacks(m_handlerTask).
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);
}
});
I want to have my runnable undate my UI every .75 second, I don't want to use AnsyTask. But the TextView is only set at the end of the for loop, any idea why?
...
robotWords = "........Hey hello user!!!";
wordSize = robotWords.length();
mHandler.postDelayed(r, 750);
}
private Runnable r = new Runnable()
{
public void run()
{
for(int i=0; i<wordSize; i++)
{
robotTextView.setText("why this words only display on the textView at last operation on this for loop?");
Log.i(TAG, robotWords.substring(0, i));
try
{
Thread.sleep(750);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
};
The TextView is only set at the end of the for loop because of this line Thread.sleep(750);
Your thread will sleep before the text is really set to your textview. I think you should call Handler.postDelayed every 750ms instead of using Thread.sleep(750); or use a CountDownTimer
new CountDownTimer(750 * wordSize, 750) {
public void onTick(long millisUntilFinished) {
robotTextView.setText("why this words only display on the textView at last operation on this for loop?");
Log.i(TAG, robotWords.substring(0, i));
}
public void onFinish() {
}
}.start();
You shouldn't be making calls to the UI thread from another thread.
use CountDownTimer
new CountDownTimer(wordSize*750, 750) {
public void onTick(long millisUntilFinished) {
robotTextView.setText("...");
}
public void onFinish() {
}
}.start();
Try this, call "doStuff()" when you want the operation to take place
public void doStuff() {
new Thread(new Runnable() {
public void run() {
for(int i=0; i<wordSize; i++) {
robotTextView.setText("why this words only display on the textView at last operation on this for loop?");
Log.i(TAG, robotWords.substring(0, i));
robotTextView.post(new Runnable() {
public void run() {
robotTextView.setText("why this words only display on the textView at last operation on this for loop?");
}
});
try {
Thread.sleep(750);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
Hope this helps!