Loading ...

Shared Preferences in android applications | CodeAsp.Net

Shared Preferences in android applications

 /5
0 (0votes)

Storing user data in an android application can be done in three ways:

1. Create a database and store data in it. (Generally used to store large data)

2. Save data in a file and save that file in your internal or external storage. (Generally preferred when you have some data that many other application might access, or you have a limitation not to use the database)

3. Save the data in a "Shared Preference", this is used to store small data, like some words, or values etc. You should not use this to load large data like whole files etc, as will be cause some issues.

Here, we will be discussing how to store data in a "Shared Preference". They are used to store small data, and follow "KEY- VALUE" value pair syntax. The system creates an "xml" file in your application folder under the folder name "shared_prefs". This file will be used to store and retrieve data.

Steps to follow:

1. Create an android studio project and name it as "Shared_Preferences", and set the company domain as "codeasp.shared_preferences.com". Click next.

2. Now select the minimum SDK as 18(Jelly Bean 4.3) and leave all other fields as they are and click next. 

3. Select the activity as Blank Activity and click next.

4. Leave all the fields as default and click next.

5. Open your "acitivity_main.xml" file from the layout file. Here, we will have to create a basic layout that we will use to store and retrieve data from the shared preferences.

6. In the "activity_main.xml" file, add the following code:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <!--  First name Label -->
    <EditText
        android:id="@+id/text_firstname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dip"
        android:hint="First Name"
        android:textAppearance="@style/TextAppearance.AppCompat.Large" />

    <!--  Last name Label -->
    <EditText
        android:id="@+id/text_lastname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dip"
        android:hint="Last Name"

        android:textAppearance="@style/TextAppearance.AppCompat.Large" />

    <!--  Phone Label -->
    <EditText
        android:id="@+id/text_phone"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dip"
        android:drawablePadding="5dp"
        android:hint="Phone Number"
        android:textAppearance="@style/TextAppearance.AppCompat.Large" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="save_data"
        android:text="Save Data" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="load_data"
        android:text="Load Data" />

    <TextView
        android:id="@+id/textView_firstname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dip"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/textView_lastname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dip"

        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/textView_phonenumber"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dip"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

7. Open your "MainActivity.java" file and create the "EditText" and the "TextView" which will be used to get data from the user and save it and then retrieve the saved data from the file.

Add the following code:

EditText text_firstname, text_lastname, text_phone;
TextView textView_firstname, textView_lastname, textView_phonenumber;

8. As you read above, "Shared Preferences" follows the KEY - VALUE pair so now let us declare some "KEY's" that we will use to refer to our data. Write the following code to do this:

    public static final String FirstName = "FirstNameSave";
    public static final String LastName = "LastNameSave";
    public static final String PhoneNumber = "PhoneNumberSave";

9. We also need to create another string that we will use for the name of the file:

public static final String SharedPreferenceDataToSave = "SharedPreferenceDataToSave";

10. Next, we need to create an object of the SharedPreferences Class that we will use for saving and loading data.

SharedPreferences sharedpreferences;

11.In the "onCreate" method we will bind our "EditText","TextView" with the xml file, as follows:

        text_firstname = (EditText) findViewById(R.id.text_firstname);
        text_lastname = (EditText) findViewById(R.id.text_lastname);
        text_phone = (EditText) findViewById(R.id.text_phone);
        textView_firstname = (TextView) findViewById(R.id.textView_firstname);
        textView_lastname = (TextView) findViewById(R.id.textView_lastname);
        textView_phonenumber = (TextView) findViewById(R.id.textView_phonenumber);

12. The next step is crucial; where we will get the instance that will store the location of the file that will have the values of the "Shared Preferences". for that we will use the method "getSharedPreferences()", in this method me need to pass the following two parameters:

1. Name of the File that we will use to save or load data.

2. The mode that will be used to create the file, which in layman terms means what permissions we will be giving to the file, e.g. whether it can be accessed  by other applications or not, or only our application, etc.

For this, add the following code:

sharedpreferences = getSharedPreferences(SharedPreferenceDataToSave, Context.MODE_PRIVATE);

After adding all the code your "onCreate" method and the declarations will look like this:

EditText text_firstname, text_lastname, text_phone;
    TextView textView_firstname, textView_lastname, textView_phonenumber;


    public static final String SharedPreferenceDataToSave = "SharedPreferenceDataToSave";
    public static final String FirstName = "FirstNameSave";
    public static final String LastName = "LastNameSave";
    public static final String PhoneNumber = "PhoneNumberSave";
    SharedPreferences sharedpreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        text_firstname = (EditText) findViewById(R.id.text_firstname);
        text_lastname = (EditText) findViewById(R.id.text_lastname);
        text_phone = (EditText) findViewById(R.id.text_phone);
        textView_firstname = (TextView) findViewById(R.id.textView_firstname);
        textView_lastname = (TextView) findViewById(R.id.textView_lastname);
        textView_phonenumber = (TextView) findViewById(R.id.textView_phonenumber);
        sharedpreferences = getSharedPreferences(SharedPreferenceDataToSave, Context.MODE_PRIVATE);
    }

13. Next, let us create two methods that we will use to save and load data. These methods will be referencing to the buttons we declared in our "activity_main.xml" file. Create them as follows:

public void load_data(View view) {
    }

public void save_data(View view) {
    }

14. Now in the method "save_data" we will add the we will first get the data from the "EditText" and then save that data. To get the data, write the code as follows:

String first_name_save = text_firstname.getText().toString();
String last_name_save = text_lastname.getText().toString();
String phone_number_save = text_phone.getText().toString();

15. Open the "Shared Preferences" file in the edit mode and add the following code:

        SharedPreferences.Editor editor = sharedpreferences.edit();

16. After this we need to put the string values using the editor to the file by adding the following code:

        editor.putString(FirstName, first_name_save);
        editor.putString(LastName, last_name_save);
        editor.putString(PhoneNumber, phone_number_save);
        editor.commit();

Next, we need to write the "editor.commit()" to save all the data to the file. After adding the whole code your method will look like this:

public void save_data(View view) {
String first_name_save = text_firstname.getText().toString();
String last_name_save = text_lastname.getText().toString();
String phone_number_save = text_phone.getText().toString();

SharedPreferences.Editor editor = sharedpreferences.edit();

editor.putString(FirstName, first_name_save);
editor.putString(LastName, last_name_save);
editor.putString(PhoneNumber, phone_number_save);
editor.commit();
Toast.makeText(MainActivity.this, "Your data has been saved.", Toast.LENGTH_LONG).show();
}

17. Now to load the data we have to use the get method and as the "String" so we will use the "getString" method and pass the KEY to get the value, write the code as follows:

        textView_firstname.setText(sharedpreferences.getString(FirstName, ""));
        textView_lastname.setText(sharedpreferences.getString(LastName, ""));
        textView_phonenumber.setText(sharedpreferences.getString(PhoneNumber, ""));

After adding the code your method will look like this:

public void load_data(View view) {
textView_firstname.setText(sharedpreferences.getString(FirstName, ""));
textView_lastname.setText(sharedpreferences.getString(LastName, ""));
textView_phonenumber.setText(sharedpreferences.getString(PhoneNumber, ""));
Toast.makeText(MainActivity.this, "Load Successful", Toast.LENGTH_LONG).show();
}

Note: In both the methods we are informing the user with a toast message that the operation has been successful.

18. Now run your application on an emulator or a physical device.

Screen Shots of running application:

                            

To download the project: Click Here

Comments (no comments yet)

Top Posts