Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

There are two EditTexts, one for name and another for email address. There are t

ID: 3850469 • Letter: T

Question

There are two EditTexts, one for name and another for email address.

There are three buttons: SAVE, RETRIEVE, and CLEAR.

The SAVE button will save the name and the email address in the SharedPreferences.

The RETRIEVE button will retrieve the name and the email address from the SharedPreferences.

The CLEAR button will clear the EditTexts.

Upon startup, the App will retrieve the name and the email address from the SharedPreferences if exist.

See the screen shots below.

SAVE RETREVE CLEAR Android Emulator News 6 API 20s554 Peter Nguyen er nguyen.sd@gmail.com SAVE PETREVE GEAR

Explanation / Answer

The code is given below :

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();