Android saving data on activity restart

In Android, when the screen is rotated, the activity gets restarted, the data can be retained in many different ways. Here are two simple data saving mechanisms.

1. For data that’s already populated on a view, for example, an EditText. If the EditText has an view id assigned to it in the layout file, and then if the user entered some text in this EditText. The user input will be retained automatically on activity restart. If there wasn’t an view id assigned to it, the user input will be lost on activity restart.

2. Save the data in the function onSaveInstanceState and retrieve the data from the function onRestoreInstanceState

class MainActivity : AppCompatActivity() {
    private var counter = 0
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        tv_counter.text = "" + counter
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        counter++
        outState.putInt(COUNTER_KEY, counter)
    }
    override fun onRestoreInstanceState(savedInstanceState: Bundle) {
        super.onRestoreInstanceState(savedInstanceState)
        counter = savedInstanceState.getInt(COUNTER_KEY)
    }

    override fun onResume() {
        super.onResume()
        tv_counter.text = "" + counter
    }

    companion object {
        private val COUNTER_KEY = "counter"
    }
}

activity_main.xml




    

    

    
    


    

    

    


Complete example in Github

Search within Codexpedia

Custom Search

Search the entire web

Custom Search