1

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

1 Answers1

1

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()
        }
    }
    ...
}
Blundell
  • 75,855
  • 30
  • 208
  • 233
  • Sir can you please elaborate it through code because I am still learning –  Feb 13 '20 at 14:24
  • I put a rough example in – Blundell Feb 13 '20 at 15:03
  • where did you use onSaveinstance? Sir in Google documentation they are showing the way I have done but when I am applying it is not working. –  Feb 13 '20 at 15:32
  • I didn't. `onSaveInstanceState` is for saving data between configuration changes. You can use that if you want, but it has nothing to do with the back button example (which uses SharedPreferences to save your data between Activities) – Blundell Feb 13 '20 at 15:38
  • See using log statements I found that when I press back button it is onDestroy is called –  Feb 13 '20 at 15:40
  • Are you using AndroidX fragments? https://developer.android.com/jetpack/androidx/releases/fragment – Blundell Feb 13 '20 at 15:43
  • Yes I used androidX –  Feb 13 '20 at 15:49
  • @AshutoshPanda If you found this helpful pls remember to upvote or mark it as answered https://stackoverflow.com/help/someone-answers – Blundell Feb 15 '20 at 23:00