Reputation: 1201
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.
Upvotes: 1
Views: 9509
Reputation: 234795
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.
Upvotes: 1
Reputation: 228
The method onCreate is mainly used for initialisation and it is called when the activity starts. Thus, only relevant initialisation code should be placed there.
You could use a onClickListener for example to increment your click counter.
This link may be of help:
http://developer.android.com/guide/topics/ui/ui-events.html
Upvotes: 1