-1

How can I save a score in my game scene even if I close the app and open it again? I'm new to android and I only know that in Swift things like that can be saved by using user defaults but I don't what to do in Android Studio.

Here is the score I want to save:

var score = 1

later in the scene ->

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    score =+ 2    //save the score here
}
Ivan Wooll
  • 4,145
  • 3
  • 23
  • 34
Luis
  • 61
  • 2
  • 12
  • 3
    You can use [shared preferences](https://developer.android.com/training/data-storage/shared-preferences). – tomerpacific Sep 08 '19 at 09:33
  • https://developer.android.com/guide/topics/data/data-storage – Henry Sep 08 '19 at 09:35
  • You can use [onSaveInstanceState](https://stackoverflow.com/questions/151777/how-to-save-an-android-activity-state-using-save-instance-state) – Krystian G Sep 08 '19 at 09:37
  • 2
    Possible duplicate of [How to use SharedPreferences in Android to store, fetch and edit values](https://stackoverflow.com/questions/3624280/how-to-use-sharedpreferences-in-android-to-store-fetch-and-edit-values) – Edric Sep 08 '19 at 09:40

1 Answers1

0

If you want to use shared preferences, you can do the following:

  • Getting the shared preferences (if you only need one shared preferences file) instance by adding this code:

    val sharedPref = activity?.getPreferences(Context.MODE_PRIVATE)
    
  • Write to shared preferences using:

    sharedPref.edit()
    putInt("Score", score)
    commit()
    
  • Read from shared preferences using:

    val score = sharedPref.getInt(getString("Score"), 0)
    
tomerpacific
  • 4,704
  • 13
  • 34
  • 52
  • I get the error from the first line-> unresolved reference: activity – Luis Sep 08 '19 at 10:04
  • @Luis - In order to get access to the shared preferences, you need to use the activity's context. If you are executing this code inside of your main activity, you can just omit the activity. – tomerpacific Sep 08 '19 at 10:30