I was trying to develop a android application in which the background changes every 5 seconds I wrote code something like this :
public class BgView extends Activity implements Runnable {
ImageView img;
int [] setImg = {R.drawable.one,R.drawable.two};
RelativeLayout layout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bg_view);
layout = (RelativeLayout) findViewById(R.id.first);
Thread t = new Thread(new BigView);
t.start();
}
@Override
public void run() {
for (int i = 0; i < 2; ++i) {
layout.setBackgroundResource(setImg[i]);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
It compiled fine but when i tried to run this in emulator it stopped after 5 seconds and in logcat
i saw an exception which says that i cannot touch Activity class view from other function or something like that.
so i put the whole for loop inside the onCreate() method and now i don't get any exception but all i see is a blank screen for 5 seconds after that i get the last image
I know this question has been repeated but i just don't want to copy paste the code...i want to know why this happened and how can we make this working with least changes
edit : i get following exception : E/AndroidRuntime(904): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
And i want to know why putting whole for loop inside onCreate() method didn't work