RedaLe
RedaLe

Reputation: 59

How can I set a simple game score using SharedPreferences?

I'm a new android developer. I've been searching for this answer all over SO for the past 4 days. I'm developing an android quiz game. There's an activity called Level 1, and several activities that can be accessed through this one (Level 1 --> Quiz 1, Quiz 2, Quiz 3...) There's a button on each of these Quiz activities, which tells the user if the Quiz is correct. If the answer is correct, a toast is showed and automatically returns to the Level 1 activity. Using SharedPreferences, I want this button to save score (each correct answer = +1 score, and that's it) and I would like to know how to display this score through a TextView all over the application. Also, is it possible to add to that same SharedPreferences a way to make an ImageView (GONE) into (VISIBLE)?

Thank you in advance. I apologize for my poor english.

Upvotes: 0

Views: 587

Answers (1)

Techwolf
Techwolf

Reputation: 1228

Yes, you can do that. Just create a SharedPreferences.Editor in Level1, and put something like this in your buttons' onClickListeners:

editor.putInt("score", prefs.getInt("score", 0))

Where editor is your SharedPreferences.Editor and prefs is your SharedPreferences object.

As for changing the imageview, you can check to see if a specific boolean is set in your SharedPreferences and change the ImageView visibility based on that. More info on SharedPreferences can be found here.

Upvotes: 1

Related Questions