Reputation: 203
I am using following code to update a list after certain time.
Myactivity {
setTimer() {
Runnable r = new Runnable() {
run() {
if(!isListUpdated) {
update();//n/w operation
} else {
show();//this is a UI operation
listupdated = false;
}
Handler.postDelayed(this,next); //repeat after next
}
new Thread(r).start();
}
}
}
After 2 - 3 iterations it is giving NetworkOnMainThreadException
. Can somebody tell what is wrong in this code?
Upvotes: 0
Views: 739
Reputation: 132992
The exception that is thrown when an application attempts to perform a networking operation on its main thread.
so you need to Use Thread, runOnUiThread, AsyncTask , Handler , or HandlerThread for Updating UI elements from background Thread.
public void myThread(){
Thread th=new Thread() {
@Override
public void run() {
try
{
while(true) {
Current_Activity.this.runOnUiThread( new Runnable() {
@Override
public void run() {
//UPDATE UI FROM HERE
}
});
}
}catch (InterruptedException e) {
// TODO: handle exception
}
}
};
th.start();
}
Upvotes: 1
Reputation: 482
I guess you are using honeycomb version, you better use AsyncTask it will solve your problem.
Upvotes: 0
Reputation: 28093
Consider using runOnUiThread
to perform UI operations in Non-UI Thread.
Your code snippet should be something like follows.
Runnable runnable = new Runnable() {
public void run() {
if (!isListUpdated) {
runOnUiThread(new Runnable() {
public void run() {
update(); //n/w operation
}
});
} else {
runOnUiThread(new Runnable() {
public void run() {
show(); //n/w operation
}
});
listupdated = false;
}
handler.postDelayed(runnable, next);
}
};
Upvotes: 1
Reputation: 4351
This exception usually occurs when you try to perform network operations in the main thread. Use an AsyncTask
for your network operations.
Upvotes: 2
Reputation: 27549
You should not do network operation in Main Thread. Create a separate thread and do nw operation there.
You can use AsyncTask, Service or separate thread . Where you ll do network operation. and update via BroadcastReceiver, Handler or AsyncTask.
Read about AsyncTask here
Upvotes: 2