I want to Change the background image of ListView automatically after a time interval :
I using this code :
in side of onCreate(_) {
t = new Thread(){
public void run() {
for(int i=0; i<=5; i++){
Log.i("forrrrr ", i+"");
try {
if(flag == 0){
listV.setBackgroundDrawable(getResources().getDrawable(R.drawable.th2));
flag = 1;
}
else if(flag == 1){
listV.setBackgroundDrawable(getResources().getDrawable(R.drawable.th1));
flag = 0;
}
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
};
t.start();
}
but i got following Exception at run time :
05-31 13:30:23.832: INFO/AndroidRuntime(309): NOTE: attach of thread 'Binder Thread #3' failed
05-31 13:30:24.442: INFO/ARMAssembler(59): generated scanline__00000077:03545404_00000004_00000000 [ 47 ipp] (67 ins) at [0x2fc6d8:0x2fc7e4] in 5635232 ns
05-31 13:30:24.723: DEBUG/dalvikvm(315): GC_EXTERNAL_ALLOC freed 882 objects / 61160 bytes in 67ms
05-31 13:30:25.332: INFO/forrrrr(315): 0
05-31 13:30:25.452: DEBUG/dalvikvm(315): GC_EXTERNAL_ALLOC freed 248 objects / 11760 bytes in 113ms
05-31 13:30:25.992: INFO/ActivityManager(59): Displayed activity com.dev/.Android10Activity: 2234 ms (total 765300 ms)
05-31 13:30:27.675: INFO/forrrrr(315): 1
05-31 13:30:27.675: WARN/dalvikvm(315): threadid=7: thread exiting with uncaught exception (group=0x4001d800)
05-31 13:30:27.675: ERROR/AndroidRuntime(315): FATAL EXCEPTION: Thread-8
05-31 13:30:27.675: ERROR/AndroidRuntime(315): java.lang.UnsupportedOperationException: removeAllViews() is not supported in AdapterView
05-31 13:30:27.675: ERROR/AndroidRuntime(315): at android.widget.AdapterView.removeAllViews(AdapterView.java:511)
05-31 13:30:27.675: ERROR/AndroidRuntime(315): at com.dev.Android10Activity$1.run(Android10Activity.java:61)
05-31 13:30:27.693: WARN/ActivityManager(59): Force finishing activity com.dev/.Android10Activity
If i used a button and change manually it working well like this :
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(flag == 0){
listV.setBackgroundDrawable(getResources().getDrawable(R.drawable.th2));
flag = 1;
}
else if(flag == 1){
listV.setBackgroundDrawable(getResources().getDrawable(R.drawable.th1));
flag = 0;
}
}
});
You can’t affect UI elements from a thread which is not a “UI Thread”.
You should run this code using Activity.runOnUiThread
or use a Handler like in this example
Here’s another article that may be useful