Reputation: 1
When I wrote my code(following) in eclipse, it gave an error on the emulator that, your application has stopped unexpectedly. There is no installation error for sdk. Here is my code.
public class startingPoint extends Activity {
/** Called when the activity is first created. */
int counter1,counter2;
Button add;
Button sub;
TextView display;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
counter1=counter2 = 0;
add = (Button) findViewById(R.id.bAdd);
add = (Button) findViewById(R.id.bSub);
display = (TextView) findViewById(R.id.tvDisplay);
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
counter1=counter1+1;
display.setText("Your total is "+counter1);
}
});
sub.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
counter2=counter2-1;
display.setText("Your total is "+counter2);
}
});
}
}
Upvotes: 0
Views: 338
Reputation: 26547
You are assigning a new value to the same variable twice.
add = (Button) findViewById(R.id.bAdd);
add = (Button) findViewById(R.id.bSub);
I think this should be :
add = (Button) findViewById(R.id.bAdd);
sub = (Button) findViewById(R.id.bSub);
In your code, sub.setOnClickListener
throws a NullPointerException
because sub
is null.
Upvotes: 1
Reputation: 29199
you are getting nullPointer exception because you havenot initialized sub variable. modify your code:
add = (Button) findViewById(R.id.bAdd);
add = (Button) findViewById(R.id.bSub);
to
add = (Button) findViewById(R.id.bAdd);
sub = (Button) findViewById(R.id.bSub);
Upvotes: 1
Reputation: 57672
You have a copy&paste error, you never initialize sub
add = (Button) findViewById(R.id.bAdd);
add = (Button) findViewById(R.id.bSub); // should be sub instead of add
For the next question, please take a look at your LogCat and post the stack trace as this might help us find the error easier.
Upvotes: 1