I made a simple application that adds 1 to the count and displays the count on a TextView. It compiled and installed fine, but when I run it, a message immediately says “Unfortunately, Counter has stopped.”
package com.android.counter;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class CounterActivity extends Activity {
/** Called when the activity is first created. */
private static int count = 0;
Button increment = (Button) findViewById(R.id.inc);
TextView tv = (TextView) findViewById(R.id.CountDisp);
Runnable update = new Runnable()
{
public void run() {
increment.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
count++;
tv.setText("Count:" + count);
}
});
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Thread thr = new Thread(update);
thr.start();
}
}
You need to set the content of the
ActivityBEFORE trying to find any of the views. Doing this……where you currently are, will mean both
incrementandtvwill benull. Change those lines to…Then use
findViewById(...)inonCreate(...)AFTER you have calledsetContentView(...)Also, using a separate
Thread(Runnable) to handle theonClick(...)listener is over complicating things and isn’t necessary. Simply create youronClick(...)listener withinonCreate(...)and forget about the other thread code.