)SharedPreferences allows activities and applications to keep preferences, in th
ID: 3850480 • Letter: #
Question
)SharedPreferences allows activities and applications to keep preferences, in the form of key-value pairs similar to a Map that will persist even when the user closes the application. Write an Android application that uses SharedPrefences to persist and to retrieve data to/from SharedPreferences respectively as described below:
• There are two EditTexts, one for name and another for email address.
• There are three buttons: SAVE, RETRIEE, and CLEAR.
o The SAVE button will save the name and the email address in the SharedPreferences.
oThe RETRIEVE button will retrieve the name and the email address from the SharedPreferences.
o The CLEAR button will clear the EditTexts.
• Upon startup, the App will retrieve the name and the email address from the SharedPreferences if exist.
Explanation / Answer
saving data
SharedPreferences pref = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
// We need an editor object to make changes
SharedPreferences.Editor edit = pref.edit();
// Set/Store data
edit.putString("username", "Rishabh");
edit.putBoolean("logged_in", true);
// Commit the changes
edit.commit();
xml file
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="username">Rishabh</string>
<boolean name="logged_in" value="true" />
</map>
retrieving data
SharedPreferences pref = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
String username = pref.getString("username", "");
boolean logged_in = String.valueOf(pref.getBoolean("logged_in", false);
Log.d(TAG, username);
Log.d(TAG, String.valueOf(logged_in));
deleting data
// Remove a particular key
pref.remove("username");
// Commit changes
pref.commit();
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.