简体   繁体   中英

How to save data when i press back button

I have made an app in kotlin through the android studio, Now I have used ViewModels to save UI data while phone rotation(configuration change), i also used onSaveInstanceState to save data while pressing back button but it's not working.

The code is below

fragOne.kt

class fragOne : Fragment() {
private lateinit var viewModel: fragViewModel

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {

    if(savedInstanceState!=null){
        with(savedInstanceState) {
        viewModel.num=getInt("number")
        }
    }

    // Inflate the layout for this fragment
    var binding = DataBindingUtil.inflate<FragmentFragoneBinding>(
        inflater,
        R.layout.fragment_fragone,
        container,
        false
    )

    viewModel = ViewModelProviders.of(this).get(fragViewModel::class.java)


    // function to update number
    fun updateNumber()
    {
        binding.number.text="${viewModel.num}"
    }

    updateNumber()

    // setting on Click listener for add button
    binding.add.setOnClickListener()
    {
        viewModel.addFive()
        updateNumber()
    }

    // setting on on Click Listener for minus button
    binding.minus.setOnClickListener()
    {
        viewModel.minusOne()
        updateNumber()
    }


    return binding.root
}




override fun onSaveInstanceState(outState: Bundle) {
    // Save the user's current game state
    outState?.run {
        putInt("number",viewModel.num)

    }

    // Always call the superclass so it can save the view hierarchy state
    if (outState != null) {
        super.onSaveInstanceState(outState)
    }
}

}

ViewModelclass

class fragViewModel:ViewModel()
{

// Initializing num=0
var num=0

// Functions to add five or subtract one

fun addFive()
{
    num=num+5
}

 fun minusOne()
{
    num=num-1
}

}

please tell me because data is not saved when I press back

You can override onBackPressed to do your state saving:

How to implement onBackPressed() in Fragments?

Remember to call super, so that is does also do the back command!

You could also do like the below:

// This callback will only be called when MyFragment is at least Started.
        val callback = requireActivity().onBackPressedDispatcher.addCallback(this) {
            // Handle the back button event
        }

Really good read: https://developer.android.com/guide/navigation/navigation-custom-back

Back navigation is how users move backward through the history of screens they previously visited. All Android devices provide a Back button for this type of navigation, so you should not add a Back button to your app's UI. Depending on the user's Android device, this button might be a physical button or a software button.

Ref:

How to show warning message when back button is pressed in fragments


Example:

Ensure your Activity extends AppCompatActivity

class MyFragment : Fragment() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        viewModel = ViewModelProviders.of(this).get(fragViewModel::class.java)

        val prefs = activity.getSharedPreferences("Key")
        int num = prefs.get("number", -999)
        if(num != -999) {
               viewModel.num = num
        }


        val callback = requireActivity().onBackPressedDispatcher.addCallback(this) {
            prefs.edit().putInt("number", viewModel.num).apply()
        }
    }
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM