What is the best way to save temporary data in android?

Asked

Viewed 81 times

-4

I’m using it this way:

val prefs = PreferenceManager.getDefaultSharedPreferences(context)

val editor = prefs.edit()
editor.putString(Constants.VENDOR_UPDATE_AT, update_date)
editor.commit()

and seeking

var update_date = PreferenceManager.getDefaultSharedPreferences(context).getString(Constants.VENDOR_UPDATE_AT, "")

Remembering that I have the context but I’m not in one Activity.

  • What it considers as "temporary data"?

1 answer

1

SharedPreferences was not made to store temporary data, but rather application settings as described in documentation android, if you want to store temporary data you should store in cache, but if you want to save this data for when the application is going to be in the background or something like that, you should use onSaveInstanceState to store this data temporarily, follow the example of documentation android:

TextView mTextView;

// some transient state for the activity instance
String mGameState;

@Override
public void onCreate(Bundle savedInstanceState) {
    // call the super class onCreate to complete the creation of activity like
    // the view hierarchy
    super.onCreate(savedInstanceState);

    // recovering the instance state
    if (savedInstanceState != null) {
        mGameState = savedInstanceState.getString(GAME_STATE_KEY);
    }

    // set the user interface layout for this activity
    // the layout file is defined in the project res/layout/main_activity.xml file
    setContentView(R.layout.main_activity);

    // initialize member TextView so we can manipulate it later
    mTextView = (TextView) findViewById(R.id.text_view);
}

// This callback is called only when there is a saved instance that is previously saved by using
// onSaveInstanceState(). We restore some state in onCreate(), while we can optionally restore
// other state here, possibly usable after onStart() has completed.
// The savedInstanceState Bundle is same as the one used in onCreate().
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
    mTextView.setText(savedInstanceState.getString(TEXT_VIEW_KEY));
}

// invoked when the activity may be temporarily destroyed, save the instance state here
@Override
public void onSaveInstanceState(Bundle outState) {
    outState.putString(GAME_STATE_KEY, mGameState);
    outState.putString(TEXT_VIEW_KEY, mTextView.getText());

    // call superclass to save any view hierarchy
    super.onSaveInstanceState(outState);
} 
  • Thank you so much for the help, thank you for the explanation! I’ll do it this way!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.