How to resolve ANR while invoking a list - android

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();
}

Related

The Timer does not accelerate when it runs for the first time, but the timer accelerates at the next working moments. How can i fix it?

public void startCountdownTimer() {
currentCountdown = startCountdown;
// stopTimer=false;
if (stopTimer == true) {
return;
}
for (int i = 1; i <= startCountdown + 1; i++) {
task = new TimerTask() {
#Override
public void run() {
countdownHandler.post(doA);
}
};
countdownTimer = new Timer();
countdownTimer.schedule(task, i * 1000);
}
}
final Runnable doA = new Runnable() {
#Override
public void run() {
//reset timer when switching to another question
if (currentCountdown != -1 && btn_next.getText().equals("CHECK") && stopTimer != true) {
if (currentCountdown == 0) {
relative_stop.setVisibility(View.INVISIBLE);
currentCountdown = startCountdown;
btn_next.setText("NEXT");
toast = Toasty.warning(getApplicationContext(), "Time's UP", 1000);
toast.show();
toast = Toasty.info(getApplicationContext(), correctAnswer, 1000);
toast.show();
countdownTimer.cancel();
countdownTimer.purge();
}
tv_timer.setText("" + currentCountdown);
currentCountdown--;
}
}
};
I'm trying to make a timer that counts down for 10 seconds, it works normally when it runs for the first time, and when it runs consecutively, the timer caused by delay suddenly speeds up.

textView not showing on first change

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);

Timer that run every seconds on android eclipse

Hi every one can you help to create a 5 seconds timer that runs for every 3 or 5 seconds.. im new in android pls help me
i have only created a 5 seconds timer but it only run once.. i want it to run for every 5 seconds..
and here is my code :
txt1 = (TextView)findViewById(R.id.textView1);
final Handler handler = new Handler();
TimerTask task = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
// pos=rand.nextInt(10);
//txt1.setText(""+pos);
if(Integer.parseInt(txt1.getText().toString()) != 0)
{
txt1.setText("" + (Integer.parseInt(txt1.getText().toString()) - 1));
}
}
});
}
};
Timer timer = new Timer();
timer.schedule(task, 1000, 1000);
Thx :)
You can do it using below code, handler calls itself again and again.
final Handler handler = new Handler();
Runnable runable = new Runnable() {
#Override
public void run() {
try{
if(Integer.parseInt(txt1.getText().toString()) != 0)
{
txt1.setText("" + (Integer.parseInt(txt1.getText().toString()) - 1));
}
handler.postDelayed(this, 3000);
}
catch (Exception e) {
// handle exception
}
}
};
handler.postDelayed(runable, 5000);

Run a AsyncTask every 10 seconds until cancelled

In my application, I have a button that starts an AsyncTask that downloads data with coordinates for google maps, then draws a marker on the map at the following coordinates. I want to run this every 10 seconds until the user presses the button again.
Here's my code for the handler:
class handleMap{
Handler mHandler = new Handler();
Runnable mTask = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while(btnRefreshPressed == false){
try{
new getGoogleMap().execute();
mHandler.postDelayed(mTask, INTERVAL);
Thread.sleep(INTERVAL);
} catch(Exception e){
System.out.println(e.toString());
}
}
}
};
public void starReapetingClass (){
hMap.starReapetingClass();
}
public void stopDoing(){
mHandler.stopDoing();
}
}
And in the menubutton where it is called:
case R.id.id_Refresh:
handleMap hMap = new handleMap();
if(btnRefreshPressed == true){
menuItem = item;
menuItem.setActionView(R.layout.progressbar);
menuItem.expandActionView();
fRun += 1;
btnRefreshPressed = false;
hMap.run();
}else if(btnRefreshPressed == false){
if(fRun > 0){
menuItem.collapseActionView();
menuItem.setActionView(null);
}
btnRefreshPressed = true;
hMap.stopHandler();
}
This currently causes the application to freeze, and the system outputs a dialog saying that the app isn't responding, and asking if I want to close or wait.
I suspect it has to with the while statement, but I don't get any errors in logcat.
Thanks in advance.
Just use:
private int mSampleDurationTime = 10000;
private boolean continueToRun = true;
mHandler.postDelayed(mRunnable, mSampleDurationTime);
where mRunnable is your task:
private final Runnable mRunnable = new Runnable() {
//...
public void run() {
...
if(continueToRun == true){
mHandler.postDelayed(mRunnable, mSampleDurationTime);
}
}
...
};
First time you call postDelayed and invoke new Runnable(). After, if you want to continue,
call the same method into run()

Why doesn't this update the screen after it is fired?

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);
}
});

Categories

Resources