Home > OS >  when I come back between screens my data is lost in kotlin?
when I come back between screens my data is lost in kotlin?

Time:12-05

The data I selected on the 1st screen is gone when I come back to the 1st screen from the 2nd screen. I want this data to still show up. How can I do that. There was a way to do this, but I don't remember exactly, so I have to ask.

I'm doing this in Kotlin by the way.

for example

1- I enter the values ​​on the first screen

2- I switch to the second screen with the help of a button

3- I go back to the first screen with the help of a button from the second

screen and the values ​​I entered are gone.

pictures

my first screen

enter image description here

my second screen

enter image description here

and when I come back

enter image description here

CodePudding user response:

I use this method that I explained bellow. I hope it works well for you.

You can use the Android ViewModel class to hold data in a lifecycle-aware way. This will allow you to keep data across fragment transactions, as the ViewModel will survive orientation changes and be cleared when the activity is destroyed. You can also use the onSaveInstanceState() method to save data in a Bundle and restore it when the activity is recreated.

Here I give you an example step by step:

  1. Create a ViewModel class which extends the Android ViewModel class. This class should contain a method for setting and retrieving data, as well as methods for handling the onSaveInstanceState() and onCreate() lifecycle methods.

     // MyViewModel.kt
     class MyViewModel : ViewModel() {
     private var myData: String? = null
    
     // Set data in the ViewModel
     fun setData(data: String) {
         myData = data
     }
    
     // Retrieve data from the ViewModel
     fun getData(): String? {
         return myData
     }
    
     // Save data in the Bundle when the activity is destroyed
     fun onSaveInstanceState(outState: Bundle) {
         outState.putString("myData", myData)
     }
    
     // Restore data from the Bundle when the activity is recreated
     fun onCreate(savedInstanceState: Bundle?) {
         if (savedInstanceState != null) {
             myData = savedInstanceState.getString("myData")
         }
     }
     }
    
  2. Create a ViewModelProvider object to create an instance of your ViewModel class.

     // Create an instance of the ViewModel class
     val viewModel = ViewModelProviders.of(this).get(MyViewModel::class.java)
    
  3. Set and retrieve data in your Activity or Fragment class.

Set data in the ViewModel

//set date in the viewModel
viewModel.setData(myData)

// Retrieve data from the ViewModel
val myData = viewModel.getData()

// Save data in the Bundle when the activity is destroyed
override fun onSaveInstanceState(outState: Bundle) {
    viewModel.onSaveInstanceState(outState)
    super.onSaveInstanceState(outState)
}

// Restore data from the Bundle when the activity is recreated
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    viewModel.onCreate(savedInstanceState)
}

CodePudding user response:

You can use Shared preference simply but depending on the type of data don't worry I got you with both

this is for primitive data types

Store in SharedPreference(your first activity) :

val preference=getSharedPreferences(preference_name, Context.MODE_PRIVATE)

        val editor=preference.edit()
        editor.putBoolean("isLoggedIn",true)
        editor.putInt("id",1)
        editor.putString("name","Alex")
        editor.commit()
        
    
 

Retrieve from SharedPreference (also in your first activity but we check if the shared is null or not if it isn't then we get the data we stored before)

      if(preference != null){
        val name = preference.getString("name", "")
        val id = preference.getInt("id", 0)
        val isLoggedIn = preference.getBoolean("isLoggedIn", false)
    }

and this is for clearing the values of the shared preference:

Context.MODE_PRIVATE).edit().clear().apply();
    

the second type of data is your custom object in other words your created class and you have to use the Gson library to do so which is going to convert your POJO to a string and then convert the string to JSON, when receiving your object it will reverse the algorithm :

this is GSON dependency for the converting:

 //Gson
implementation 'com.google.code.gson:gson:2.8.9'

Store in Gson SharedPreference :

val sharedPreferencesToJson =
                getSharedPreferences(
                    "preference_name", Context.MODE_PRIVATE
                )

            val object = Customer() // your object what ever it is
            object.cMobile = mobile
            object.cImage = imageUri.toString()
            val edit = sharedPreferencesToJson.edit()

            val gsonCustomer = Gson()
            val json = gsonCustomer.toJson(`object`)
            edit.putString(/*your object lable*/, json)
            edit.apply()

Retrieve from Gson SharedPreference:

val sharedPreferences =
            getSharedPreferences(
                "preference_name", MODE_PRIVATE
            )
        val gson = Gson()
        if (sharedPreferences != null)
        {
            val json: String = sharedPreferences.getString(/*your object lable*/, "")!!
            object = gson.fromJson(json, Customer::class.java)
        }

Clear Gson SharedPreference :

 this.getSharedPreferences(Constants.MY_SHOP, Context.MODE_PRIVATE).edit().clear().apply();
  • Related