Reputation: 167
I have several buttons which take me to the same activity. And I would that particular counter is increased depending on which button is touched(from the previous activity). How do I know which button is touched without give error: Example code with only two buttons. Activity A:
btnSi.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
sumarSi=true;
Intent aSiguiente = new Intent(Peliculas.this, ResultadosSiguientes.class);
aSiguiente.putExtra("sumarSi", sumarSi);
startActivity(aSiguiente);
Peliculas.this.finish();
}
});
btnNo.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
sumarNo=true;
Intent aSiguiente = new Intent(Peliculas.this, ResultadosSiguientes.class);
aSiguiente.putExtra("sumarNo", sumarNo);
startActivity(aSiguiente);
Peliculas.this.finish();
}
});
Activity B (Oncreate):
Bundle extras = getIntent().getExtras();
Boolean r1 = extras.getBoolean("sumarSi");
if(r1==true){
rdo1++;
}
Boolean r2 = extras.getBoolean("sumarNo");
if(r2==true){
rdo2++;
}
This gives me error because when I play btnSi button and go to the Activity B, extras.getBoolean("sumarNo"); fails because there is no data to receive. How I can fix?
Upvotes: 0
Views: 44
Reputation: 12365
You choose wrong way to mark which button was clicked
btnSi.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent aSiguiente = new Intent(Peliculas.this, ResultadosSiguientes.class);
aSiguiente.putExtra("button", 1);
startActivity(aSiguiente);
Peliculas.this.finish();
}
});
btnNo.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent aSiguiente = new Intent(Peliculas.this, ResultadosSiguientes.class);
aSiguiente.putExtra("button", 2);
startActivity(aSiguiente);
Peliculas.this.finish();
}
});
And in Activity A in onCreate() method change to:
Bundle extras = getIntent().getExtras();
int r = extras.getInt("button", -1);
if(r==1){
rdo1++;
}
if(r==2){
rdo2++;
}
Upvotes: 1