HyperX HyperX - 2 months ago 19
Android Question

Counting button clicks

I'm just writing little program which will count click and display it in a textview when you click button. Here is my code:

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.view.View.OnClickListener;


public class Vaje01Activity extends Activity {
/** Called when the activity is first created. */

EditText txtCount;
Button btnCount;
int count = 0;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

txtCount = (EditText)findViewById(R.id.textView1);
txtCount.setText(String.valueOf(count));
btnCount = (Button)findViewById(R.id.button1);

btnCount.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
count++;
txtCount.setText(String.valueOf(count));
}
});

}
}


So when I try to run this it gives me an unexpected error that it has stopped, but in code there are no errors.

Answer

There are really only a couple of possibilities here. One possibility is that your main.xml layout is missing an element with id textView1 or button1, in which case you are getting a NullPointerException. The other (and this is my guess) is that the element with id textView1 is declared in the XML as a TextView instead of an EditText, in which case you are getting a ClassCastException.