I am doing a quiz, in that I have 3 activities Question1, Question2, Question3,and on each there is 4 possible answers (buttons), only one button is correct. I must calculate and display the score of the user at the end of the quiz.
I have done some research and SHAREDPREFERENECES seem to be the solution. But i dont know how to use it can anyone help please. Question1.java code is below: Assume that btnAnswer1a is the correct answer, how do i save the data and then display it in a textview in the last activity.
Button Answer1, Answer2, Answer3, Answer4;
public static final String PREFS_NAME = "MyPrefsFile";
static SharedPreferences settings;
SharedPreferences.Editor editor;
int ScoreCount;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.answer1);
settings = getSharedPreferences(PREFS_NAME, 0);
editor = settings.edit();
ScoreCount = settings.getInt("ScoreCount", 10);
Answer1 = (Button) findViewById(R.id.btnAnswer1a);
Answer2 = (Button) findViewById(R.id.btnAnswer1b);
Answer3 = (Button) findViewById(R.id.btnAnswer1c);
Answer4 = (Button) findViewById(R.id.btnAnswer1d);
Answer1.setOnClickListener(this);
Answer2.setOnClickListener(this);
Answer3.setOnClickListener(this);
Answer4.setOnClickListener(this);
}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {
case R.id.btnAnswer1a:
Intent Screen1 = new Intent(Answer1.this, Color2.class);
Answer1.this.startActivity(Screen1);
editor.putInt("ScoreCount", 6);
editor.commit();
break;
case R.id.btnAnswer1b:
Intent Screen = new Intent(Answer1.this, Color2.class);
Answer1.this.startActivity(Screen);
break;
case R.id.btnAnswer1c:
Intent Screen3 = new Intent(Answer1.this, Color2.class);
Answer1.this.startActivity(Screen3);
break;
case R.id.btnAnswer1d:
Intent Screen2 = new Intent(Answer1.this, Color2.class);
Answer1.this.startActivity(Screen2);
break;
}
When you want to write something to SharedPreferences use this
And to read something from them just do this
resultValue is your quiz result and defaultValue is needed in situation when you didn’t write anything to sharedPreferences under that key.