Professional Documents
Culture Documents
Android provides the SharedPreferences object to help you save simple application
data. Using the SharedPreferences object, you can save the data you want through the use
of key/value pairs — specify a key for the data you want to save, and then both it and its
value will be saved automatically to an XML file
TRY IT OUT: Saving Data Using the
SharedPreferences Object
You can use gson.jar to store class objects into SharedPreferences. You can download
this jar from google-gson
Or add the GSON dependency in your Gradle file:
implementation 'com.google.code.gson:gson:2.8.8'
Creating a shared preference:
In the main.xml fi le, add the following code in bold (replacing the existing TextView):
<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:orientati ion=”vertical” >
main.xml fi le
<Button
android:id=”@+id/btnPreferences”
android:text=”Load Preferences Screen”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:onClick=”onClickLoad”/>
main.xml fi le
<Button
android:id=”@+id/btnDisplayValues”
android:text=”Display Preferences Values”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:onClick=”onClickDisplay”/>
<EditText
android:id=”@+id/txtString”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”/>
main.xml file
<Button
android:id=”@+id/btnModifyValues”
android:text=”Modify Preferences Values”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:onClick=”onClickModify”/>
</LinearLayout>
package