Gerald W
Gerald W

Reputation: 3

How does application storage work on android?

I'm creating an android application where a user can input their name, which would saved after closing out the application entirely. Do I need to do more work beyond just changing the methods like oneResume(), onPause(), etc. or is there a specific way to save this across sessions?

Upvotes: 0

Views: 50

Answers (2)

praveen2034
praveen2034

Reputation: 119

In Android Session management can be done through SharedPreference. You have to store and retrieve the data according to the activity life cycle. As mentioned below

Upvotes: 0

Khemraj Sharma
Khemraj Sharma

Reputation: 58934

You have to code for that. Good thing is Android provide apis for everything. You can use SharedPreference for saving data.

Store values in preference in onPause():

// PREFERENCE_NAME - a static String variable like: 
//public static final String MY_PREFS_NAME = "MyPrefsFile";
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
 editor.putString("name", "abc");
 editor.apply();

Retrieve data from preference onResume():

SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); 
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
  String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
}

https://developer.android.com/training/data-storage/shared-preferences

Note that if you want save huge data like a list of cities, then use database.

https://developer.android.com/reference/android/database/package-summary

Upvotes: 1

Related Questions