Download the New LearnVern Android App and enter Lucky Draw to win Free Certificate
If you are facing any issue in playing video please use Firefox browser.
Now we will look there how Shared Preference works practically, so for that, we will design an application.
First of all, we will make a project name 'sharedpreference', and in this, we will take three editText and two buttons.
button1 - 'Save'
button2 - 'Reset'
Now when we look in 'main.xml' file, we have used linear layout, three edit Texts, and two Buttons, and we have added all the basic properties to them including their IDs.
Now we will see that how we are generating the code, so for that we will use two different types of class in our Java file,
In PreferenceConnector class, we have declared some strings,
public class PreferenceConnector
public static final String PREF_NAME=""PEOPLE_PREFERENCES"";
public static final int MODE = Context.MODE_PRIVATE;
public static final String NAME = ""NAME"";
public static final String SURNAME = ""SURNAME"";
public static final String AGE = ""AGE"";
Now we will use a method known as Editor in our code,
public static void writeInteger(Context context,String key,int value)
public static void writeString(Context context,String key,int value)
public static Editor getEditor(Context context)
Now to read integer and string we have to design a method for that,
public static void readInteger(Context context,String key, int defvalue)
Similarly, we will design for the string.
Now we will look for a PreferencesActivity, for that, we have set the layout firstly, and after that, we have used a method 'init()' in which we have done view identification for editText we are using.
After that we have used a Save method,
public void save (View view)
And then we have used 'if' statement individually for Name, Surname and Age. In which we have used 'PreferenceConnector.writeString' and 'PreferenceConnector.writeInteger' to check the condition and pass Name, Surname and Age.
Now for reset button we want to clear our content so for that, we are using, PreferenceConnector.getEditor(this).remove(PreferenceConnector. //content// )
After that, we have created a method 'readPerson', which we have called in our 'init()' method. This method will clear our content if it is not saved. This can also be used to retrieve our content that we have stored once.
Now we will execute our code, when it is executed it is looking as per we expected, three content fields and two buttons, and our program is working successfully.
Have a friend to whom you would want to share this course?