Search code examples
androidfragmentviewmodellifecycle

Keep Bitmap in ImageView when Change Fragment with ViewModel


I have two Fragment that I bundle bitmap between them.

in FragmentA, I select Image From Gallery and Camera and set it in ImageView as Bitmap

and I will bundle that bitmap when I navigate to HomeFragmrnt and get it and Set it in ImageView in HomeFrag as Bitmap again!

PROBLEM: When I leave the FragmentA to FragmentB and back again to SettingFrag I lose the ImageView! and when I leave the FragmentB I lose the image again!

I know it is for Fragment Lifecycle and I try to use savedInstance but do not work!

I have ViewModel class for FragmentA and FragmentB ! how can I handle my problem with it ?!

if you want any code I will post it!

Thank you


Solution

  • I solved the problem tnx @parag Pawar

    I used SharedPrefrences! Just it!

    I put the Image File in SharedPrefrences and get it in another Fragment! The Image Saved and everything was good!

       lateinit var preferences: SharedPreferences
        lateinit var editor: SharedPreferences.Editor
    
    
        companion object {
     const val PREF: String = "PREF_KEY"
            const val IMG_KEY: String = "IMG_PATH"
    }
    
    
    
        preferences = activity!!.getSharedPreferences(PREF, Context.MODE_PRIVATE)
        editor = preferences.edit()
    
    
    
     editor.putString(IMG_KEY, data.data.toString())
                        editor.apply()
    

    //here u get the value

        val sharedPreference: SharedPreferences = activity!!.getSharedPreferences(
            PREF, Context.MODE_PRIVATE
        )
        if (sharedPreference.contains(IMG_KEY)) {
            imgPath = sharedPreference.getString(
                IMG_KEY,
                null
            ).toString()
        }