In this when the user clicks on the button a thread named "startAThread" starts and the button becomes invisible. After three seconds When the thread has done its work the button again becomes visible. When the user clicks on the button the second time it gives the error in LogCat:
Code:-
public class MainActivity extends Activity {
Handler mHandler;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
mHandler = new Handler(Looper.getMainLooper());
button.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
startAthread.start();
button.setVisibility(View.INVISIBLE);
}
});
}
Thread startAthread = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
Thread.sleep(3000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
mHandler.post(new Runnable()
{
@Override
public void run()
{
button.setVisibility(View.VISIBLE);
}
});
}
});
}
Logcat:-
01-10 19:45:39.861 22473-22473/com.guptamanish712.threadtest W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x418002b8)
01-10 19:45:39.891 22473-22473/com.guptamanish712.threadtest E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.IllegalThreadStateException: Thread already started.
at java.lang.Thread.start(Thread.java:1045)
at com.guptamanish712.threadtest.MainActivity$1.onClick(MainActivity.java:29)
at android.view.View.performClick(View.java:4295)
at android.view.View$PerformClick.run(View.java:17456)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:174)
at android.app.ActivityThread.main(ActivityThread.java:4952)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
at dalvik.system.NativeStart.main(Native Method)