Skip to content Skip to sidebar Skip to footer

Save Changes In Activity Onpause()

am having an activity which has a recycler view that displays data fetched from database , it displays products to add in cart so user sets the quantity of the product . all good h

Solution 1:

Yes its good idea to avoid losing data or state.

  1. Save Instance state by Implementing onSaveInstanceState Method.

    @Override 
     protected void onSaveInstanceState(@NonNull Bundle outState) {
     super.onSaveInstanceState(outState);
     outState.putString("productName",productText.getText().toString());
     outState.putInt("quantity", Integer.parseInt(quantityText.getText().toString())); 
    }
    
  2. Restore in onCreate.

    if (savedInstanceState != null) {
         productText.setText(savedInstanceState.getString("productName"));
         quantityText.setText(String.valueOf(savedInstanceState.getInt("quantity")));
    
     }
    

Solution 2:

Instead of using SharedPreferecnes, use the ViewModel class that specific purpose is to store and manage UI-related data in a lifecycle-conscious way. The ViewModel class allows data to survive configuration changes such as screen rotations. enter image description herehttps://developer.android.com/topic/libraries/architecture/viewmodel

Post a Comment for "Save Changes In Activity Onpause()"