How to Use SharedPreference in Android to store, fetch, and delete data?

There are many ways to store, fetch, and delete data Shared Preference is mostly used to store value in key pair value.

Through this you can save some configuration.

So I Have prepare tutorial for SharedPreference in JAVA langauage

First I’ll share you the activity_main.xml file.

How to Use SharedPreference

App Design is very simple you have two EditTextbox, TextView and Buttons.

So basically our app will take inputs from the user and data will store in shared preference after that we will fetch out data from the app and delete the saved data too.

We have assigned all the variable above the onCreate method.

 private String NAME_KEY = "NameOfPerson";
 private String LEARNING_KEY = "StudyName";

Shared Preference require key so assign the key Variable name.

private String mName;
private String mStudyName;

Assign two String Value .

Assign Shared Preference and pass the value you can but any name usually we prefer to provide appActivity Name.

private SharedPreferences mPreferences;
    private String sharedPrefFile =
            "com.example.sharedpref";

Now initialize every variable in Oncreate.

After this when user press the save button mName and mStudy will get the value of input.

Now call SharedPreference.Editor and start in edit

in putString give the KEY and Value we have two to option one for name and another for what is studying

To close shared preference edit option add preferenceEditor.apply().

Inside this create callSaveDetails method which will help you to show the data.

We will take out data from save preference and will show in textView

After this if user want to clear the share preference data he press on clear button data will be wiped

Even If I closed the app or rotate the device data will not get wiped. This was the one example of sharedPreference if you want to download source code you can download and use.

Leave a Reply