Reputation: 11
I'm new in Android Development. I reviewed the automatic click button post before but I still cannot configure the these error. The App Stop Working after 5 secs timer.
Below is my code on MainActivity:
package com.example.cynog.autobutton;
import android.content.Intent;
import android.content.res.Resources;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
private Button button1;
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
performClick();
Thread timer = new Thread(){
public void run(){
try{
sleep(5000);
} catch (InterruptedException e){
e.printStackTrace();
}finally{
button1.performClick();
}
}
};
timer.start();
} catch (Resources.NotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void performClick() {
button1 = (Button) findViewById(R.id.button);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, activity.class);
startActivity(i);
}
});
}
}
And This is my XML:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.cynog.autobutton.MainActivity">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:onClick="performClick"
tools:layout_editor_absoluteX="153dp"
tools:layout_editor_absoluteY="209dp" />
</android.support.constraint.ConstraintLayout>
Upvotes: 0
Views: 2087
Reputation: 345
Button is created in the ui thread that is main thread.
so if u want to make any action with it do it inside handler.post(new Runnable(){void run(){//perform action here}
. make a Handler object in oncreate(). Handler handler=new Handler().
and put the handler.post() code in the timer thread run method after sleep. I hope it works.
Upvotes: 1