I am trying to use the getIntent value(score) which is retrieve from the previous activity but it seems like it is impossible. It seems that addition and subtraction under if else cannot detect score. Is there any other way?
package com.mkyong.android;
import com.mkyong.android.R;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View;
import android.view.View.OnClickListener;
public class App2Activity extends Activity {
private RadioGroup radioAnswerGroup2;
private RadioButton radioAnswerButton2;
private Button btnSubmit2;
Button button2;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
addListenerOnButton();
}
public void addListenerOnButton() {
final Context context = this;
radioAnswerGroup2 = (RadioGroup) findViewById(R.id.radioAnswer2);
button2 = (Button) findViewById(R.id.button2);
Button button2pre = (Button) findViewById(R.id.button2pre);
Intent intent = getIntent();
final int score = intent.getIntExtra("int", -1);
final TextView result2 = (TextView) findViewById(R.id.txtResult2);
result2.setText("Result counting: " + String.valueOf(score));
button2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int correctId2 = (R.id.answer2b);
// get selected radio button from radioGroup
int selectedId2 = radioAnswerGroup2.getCheckedRadioButtonId();
// find the radio button by returned id
radioAnswerButton2 = (RadioButton) findViewById(selectedId2);
if (selectedId2==correctId2){
score = score + 1;
//show toast saying it is correct
//Context context = getApplicationContext();
//CharSequence text = ("You are correct!");
//int duration = Toast.LENGTH_SHORT;
//Toast toast = Toast.makeText(context, text, duration);
//toast.show();
}
else{
score = score - 1;
//toast incorrect
//Context context = getApplicationContext();
//CharSequence text = ("You are wrong but it's ok and the answer is Data Link");
//int duration = Toast.LENGTH_LONG;
//Toast toast = Toast.makeText(context, text, duration);
//toast.show();
}
Intent intent2 = new Intent(App2Activity.this, App3Activity.class);
intent2.putExtra("int", score);
startActivity(intent2);
}
});
button2pre.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent(context, AppActivity.class);
startActivity(intent);
}
});
}
}
Simply remove
final
keyword from :Because a
final
variable can only be initialized once, either via an initializer or an assignment statement.Read more here.
Move
int score
to be a global variable to access it in onClick. You'll also need to remove thefinal
keyword so the value can be changed after you initialize it.