Search code examples
androidkotlinonsaveinstancestate

how can i put drawable in onSaveInstanceState


I am using onSaveInstanceState to save a data item and I need to save a drawble as well, but there's no method called putDrawable. Therefore, how can I store a drawable in a Bundle?

This my code:

override fun onSaveInstanceState(outState: Bundle) {
    super.onSaveInstanceState(outState)
    outState.putParcelable("item", item)
    outState.putDrawable("drawable", drawable) // This line is not compiling
}

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
    item = savedInstanceState?.getParcelable("item") ?: item
    return super.onCreateDialog(savedInstanceState)
}

Solution

  • There is NO way you can pass a drawable in a android.os.Bundle.

    What you can instead do is to create a class with a static object of drawable. You can store the drawable in it when onSaveInstanceState() triggers. And then use the same class to retrieve back the drawable. The code given below will explain better:

    1. The additional class

      class VariablesHelper(){
         companion object{
            var drawable?: Drawable =  null
         }
      }
      
    2. For setting the drwable

      override fun onSaveInstanceState(outState: Bundle) {
         super.onSaveInstanceState(outState)
         VariablesHelper.drawable = drawable
      }
      
    3. For getting the drawable, use

      val drawable?:Drawable = VariablesHelper.drawable