0

So i have a project and want to save a value when the user quits the app and i tried to copy code from the google lemonade project like this:

class MainActivity : AppCompatActivity() {

    private val LEMONADES = "LEMONADES"
    private val TOTAL_LEMONADES = "TOTAL_LEMONADES"

    private var lemonades = 0
    private var total_lemonades = 0

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

        if (savedInstanceState != null) {
            lemonades = savedInstanceState.getInt(LEMONADES, 0)
            total_lemonades = savedInstanceState.getInt(TOTAL_LEMONADES, 0)

            //some code to format the vals
        }
    }

    override fun onSaveInstanceState(outState: Bundle) {
        outState.putInt(LEMONADES, lemonades)
        outState.putInt(TOTAL_LEMONADES, total_lemonades)
        super.onSaveInstanceState(outState)
    }
}

So am i doing the code wrong or i should use something else?

a_local_nobody
  • 7,947
  • 5
  • 29
  • 51
Cyao
  • 727
  • 4
  • 18
  • 1
    https://developer.android.com/training/data-storage – a_local_nobody Feb 20 '22 at 15:19
  • 1
    lots and lots of resources available online for how to store values into persistent storage, copying code from another project without having an understanding of what it doesn't isn't going to get you very far – a_local_nobody Feb 20 '22 at 15:23
  • For user preferences (themes, names, colors, dates and other simple values) you can use `Shared Preferences`. For other (more complex or larger) data, you can either save to a text file into app storage (easier, more primitive with no search and indexing) or a room database (an SQL database). – mcy Feb 21 '22 at 08:47
  • Does this answer your question? [How to save data in an android app](https://stackoverflow.com/questions/10962344/how-to-save-data-in-an-android-app) – Ivo Feb 21 '22 at 08:59

1 Answers1

1

see this for shared references:

https://developer.android.com/training/data-storage/shared-preferences

cyao1234
  • 40
  • 1
  • 8