I have a small Android application that automatically clicks the button after 5 seconds. I have used performClick();
but this does not work. When the timer gets
Use the runOnUiThread()
method. This method run your method of UI thread
You should post your logcat that includes the error message but one issue might be that you are accessing a UI element off the UI thread which isn't a good idea.
To do what you want you really don't need another thread. You can use a Handler
and a delayed Runnable
instead like below.
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
button1.performClick();
}
}, 5000);
This will schedule the Runnable
to be executed on the UI thread after 5 seconds. If that still crashes post the stack trace from logcat.
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.local);
getActionBar().setIcon(R.drawable.menu_drop);
//buttonClick();
Thread timer = new Thread(){
public void run(){
try{
sleep(5000);
} catch (InterruptedException e){
e.printStackTrace();
}finally{
//button1.performClick();
getLocationOnClick();
}
}
};
timer.start();
} catch (NotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Change you button click method to like this -
public void getLocationOnClick(View v) {
Intent i = new Intent(TestButton2.this, LocationView.class);
startActivity(i);
}
In the xml for your Button add an onClick attribute -
<Button
android:id="@+id/btnid"
android:onClick="getLocationOnClick"
.... >