I have been tracing down a problem where a block of my code just stops working. At long last, I identified the line, as seen below:
Log.v(TAG,"Here");
tv.setText("");
Log.v(TAG,"There");
During the time that blocks, the first statement gets called, the second one doesn't. Any idea what could be causing this?
In case there's any doubt, tv is a TextView. There is no errors printed out, and in fact, this line worked once previously...
I figured out what my problem was, I'm posting the answer here to help anyone out in the future. It might be an Android bug, or something odd... No error was ever posted. Bottom line is, don't make GUI calls in a ScheduledThreadPoolExecutor.
ScheduledThreadPoolExecutor masterExecutor;
masterExecutor=new ScheduledThreadPoolExecutor(1);
masterExecutor.schedule(new Runnable(){
#Override
public void run() {
//Formerly, I ran the block of code here, that blocked.
runOnUiThread ( new Runnable()
{
#Override
public void run() {
//Now I moved the code inside of a runOnUiThread
}
});
}
},1000,TimeUnit.MILLISECONDS);
Related
This is my first Android application and I am finding troubles with while loop, I am trying to use a while loop on my Android application but the application freezes.
What I'm trying to do is track the user location (using onlocationChanged) and keep querying on the location until the query returns a result. It's a GIS application so I am going to describe the application behavior:
the application keeps tracking the user position using a listener "onLocationChangedListener" and store it in a variable "myPosition". I am using a boolean"noResults=true". I will use a method "query(myPosition)" in the while loop, this method has a callback that when a result is found, and changes a boolean "noResults" to false. the loop will keep on until "noResults" is false (that means query's callback changed the boolean's value)
, here's what I did:
while(noResults)
{
//myPosition keeps changing
query(myPosition);
//query has a callback that when a result is found it changes noResults to false
}
I resolved the problem using a "Handler" that query the Feature Layer every 5 seconds, this stops the main thread from generating application not responding error:
Handler m_handler=new Handler();
Runnable m_runnable;
m_runnable = new Runnable(){
public void run() {
//query code here
m_handler.postDelayed(m_runnable, 5000);
}
};
m_handler.postDelayed(m_runnable, 0);
running while loop codes on the main thread freezes the UI, and makes all other processes pause making your app unresponsive use
Threads..
also note that the while loop you are running is running on a default Thread termed as the ui thread so in short run while loops on separate threads..
eg..
new Thread(new Runnable() {
#Override
public void run() {
// Your hard while loop here
//get whatever you want and update your ui with ui communication methods.
}
).start();
for ui communicating methods
View.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), "updated ui", Toast.LENGTH_LONG).show();
}
});
the view could be any views you are updating..
also like #TehCoder said you could use asynctask but asynctask is not meant for long workaflow work there are 3 of them but i can't recall the last one
Maybe you should use an AsyncTask? I'm not quite sure what your problem is tho.
Loop is not a problem in android (or any language).
There are two scenario might be reason for your freezing,
If you run network call in api, android throw error and crashes. You have to do network related calls in Aysnc Task ot threading
Use try throw catch and exception cases to avoid app crashing and better coding skill.
I'm trying to get a short time break with a Handler. I made a test like this:
Log.i("Test","Brake start!");
handler1.postDelayed(this, 500);
Log.i("Test","Brake end!");
But there seems to be no break! The text in LogCat is running constantly. I need this short break to move a sprite object to a certain position and then make a check, but without any breaks the code is doing it all at once and the sprite object does not reach it's target before the check has been done.
Am I using the Handler incorrectly or is there a better way to get a short break? I'm running my code inside a game loop in a class that implements Runnable. Looking forward to get some tips!
Try this:
Log.i("Test","Brake start!");
handler1.postDelayed(new Runnable() {
public void run() {
Log.i("Test","Brake end!");
}
}, 500);
I'm using Handler and HandlerThread to perform asynchronous loading in my application, but something is going wrong, for example:
handler.postDelayed(new Runnable() {
#Override
public void run() {
.....................
}
}, 100);
this handler wrip (sic) in a new HandlerThread and is created in onCreate().
It seems like that is no problem, however there are times when an error appears, one example of this is a NullPointerException caused on this handler - it is stable before - but when I test on 2.1 version emulator this happen some times and I can't solve it, is thee any one that can help me?
have you considered race conditions in your code? it sounds like the handler code is not performing proper synchonization - and might sometimes see changes from a different thread - which again causes your nullPointer exception.
try wrapping your problem code in a synchonized block - or if you are using primitve types only - move to volatile or atomic types.
I have some code that will not run if I don't have a breakpoint. My speculation is that the code gets executed too quickly, and the time between me allowing a breakpoint to continue lets a thread lock on to my code. It also doesn't get "caught" with my exception handling, so its not bad code, but when the breakpoint is there it will dive into the try further and do everything I want it to do
not sure how to get this to work without being in debug mode! I am considering wait() or sleep() functions but it seems like a silly workaround, let me know if there is a better way
Thread triggerService = new Thread(new Runnable(){
public void run(){
Looper.prepare();
try{
// ....... code here does not get executed
// such as if statements or anything
Looper.loop();
}catch(Exception ex){
System.out.println("Exception in triggerService Thread -- "+ex);
}//end catch
}//end run
}, "myNewThread");
triggerService.start();
Insight appreciated!
Code works fine for me. Is there any other code in you program? Have you inserted debug output? You could test if the run() method is executed.
Let's say in various points in my application, I create and fire off a new runnable like so:
new Thread(new Runnable() {
public void run() {
while(true) {
//do lots of stuff
//draw lots of stuff on screen, have a good ol time
//total loop processing time abt 1250-1500ms
//check for conditions to stop the loop, break;
} } }
Now, is there any way to terminate that thread midway through execution other than break; inside my while loop? I'd like to be able to kill it specifically and immediately from the parent thread, like, as in the event that the user just requested to load a different map. It feels clunky to insert an if (stopFlag) break; (set in parent thread) after every 5 or so lines of code.
I peeked at Runnable's and Thread's methods and I just can't see it. Someone know an awesome trick?
You may use AsyncTask and call cancel to cancel the thread.
Instead of while (true) you may check for a condition or a flag that would be changed properly when the Thread/Runnable should be stopped. This seems to be the suggested strategy since Thread.stop() has been deprecated.
You could use AsyncTask as suggested, which probably works best in this case. I believe you can also use the interrupt() method, which is preferred if good if you're not in Android, but still suffers from having to explicitly check if it is interrupted:
Thread t = new Thread(new Runnable() {
public void run() {
while (true) {
// do some stuff
if (isInterrupted()) {
break;
}
}
});
t.start();
// Whoa! Need to stop that work!
t.interrupt();