MrBool
You must be logged in to give feedback. Click here to login
[Close]

You must be logged to download.

Click here to login

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to implement Shared Preferences in Android

In this tutorial we are going to learn about the shared preferences feature in Android.

[close]

You didn't like the quality of this content?

Would you like to comment what you didn't like?

Basically shared preference in android are used to save the state of an activity or to save the important data within the scope of an application means data will remain saved till the application is installed in the devices. Shared Preference also works as Sessions which are used for the automatic login process.

Objective:

  • To provide knowledge to the viewer how to use shared preference in android.
  • To give basic introduction and usage of Editor in android.
  • To provide knowledge to the viewer how to pull out files from Android Emulator.

Classes Used in this project :

  • SharedPreferences Interface.
  • Editor Interface.

Introduction to classes used :

SharedPreferences Interface : This class is used to implement the shared preferences feature in android. It is used for accessing and modifying the data which is returned by the getSharedPreferences (String, int) method. All the class can share the only one instance of this class for the implementation. Here are below some commonly used methods:

  • abstract boolean contains(String key) : This method is used to get the result in either true or false which will tell that whether ‘key’ holding SharedPreferences exits or not. It will return true it key exists.
  • public Abstract SharedPreferences getSharedPreferences(String nm, int mode) : This method will retrieve and hold the contents of the preference file ‘nm’, returning a SharedPreference through which a developer can modify and retrieve its content values. The instance of the SharedPreference object will return only to any caller for the same name.

String nm : This is the user define name for accessing and modify the SharedPreferences data.

int mode : This is the operating mode. 0 is default for the MODE_PRIVATE.

abstract long(String key, long value) : This method is used to reterive a long value from the SharedPreferences.

Editor Interface: This is the interface which is used for the modification of SharedPreferences contents. All changes that a developer makes in an editor are batched and changes are not copied back to original again. Changes will not reflect until commit () or apply() method not called. Here are below some important method that are used :

  • abstract void apply() : By calling this method, data will be modified permanently.
  • abstract boolean commit() : This method return true if changes have made and reflect changes on call.
  • abstract SharedPreferences.Editor clear() : This method is used to remove all values from the SharedPreferences.
  • abstract SharedPreferences.Editor putBoolean(String key, boolean value) : This method will set the boolean value in SharedPreferences with key for the retrieval of value.
  • abstract SharedPreferences.Editor putString(String key, String value): This method is used to put the String value in SharedPreferences and key is to retrieval of the value.
  • abstract SharedPreferences.Editor remove(String key) : This method is used to remove the value that is holding the key.

Steps that are used to complete this project :

Create a new Android Project and name it “SharedPrefernces”.

Shows Project name is SharedPrefernces

Figure 1 : Shows Project name is SharedPrefernces

Give package name to it “com.jmd.sharedpreferences”.

Shows Package name should be com.jmd.sharedpreferences

Figure 2 : Shows Package name should be com.jmd.sharedpreferences

Listing 1 : Paste the following code inside the main.xml file which will create the UI Portion.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:padding="5px" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text="Shared Preferences Login"
        android:textSize="20px" />

    <TextView
        android:id="@+id/usertext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="100px"
        android:text="USERNAME"
        android:textSize="20px" />

    <EditText
        android:id="@+id/userinput"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/usertext"
        android:layout_toRightOf="@+id/usertext" />

    <TextView
        android:id="@+id/userpass"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/usertext"
        android:layout_marginTop="50px"
        android:text="PASSWORD"
        android:textSize="20px" />

    <EditText
        android:id="@+id/passinput"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/userpass"
        android:layout_toRightOf="@+id/userpass"
        android:inputType="textPassword" />

    <Button
        android:id="@+id/submit"
        android:layout_width="100px"
        android:layout_height="wrap_content"
        android:layout_below="@+id/userpass"
        android:layout_marginTop="60px"
        android:text="Submit" />

    <Button
        android:id="@+id/exit"
        android:layout_width="100px"
        android:layout_height="wrap_content"
        android:layout_below="@+id/userpass"
        android:layout_marginLeft="110px"
        android:layout_marginTop="60px"
        android:layout_toRightOf="@+id/submit"
        android:text="Exit" />

</RelativeLayout>

Listing 2: Paste the following code inside the SharedPreferncesActivity.java file. It contains all the code and events.

package com.jmd.sharedpreferences;

import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SharedPreferncesActivity extends Activity implements
		OnClickListener {

	Button submit, exit;
	String username, password;
	EditText userinput, passinput;
	SharedPreferences sh_Pref;
	Editor toEdit;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		getInit();
	}

	public void getInit() {
		submit = (Button) findViewById(R.id.submit);
		exit = (Button) findViewById(R.id.exit);
		userinput = (EditText) findViewById(R.id.userinput);
		passinput = (EditText) findViewById(R.id.passinput);
		submit.setOnClickListener(this);
		exit.setOnClickListener(this);
	}

	public void sharedPrefernces() {

		sh_Pref = getSharedPreferences("Login Credentials", MODE_PRIVATE);
		toEdit = sh_Pref.edit();
		toEdit.putString("Username", username);
		toEdit.putString("Password", password);
		toEdit.commit();

	}

	@Override
	public void onClick(View currentButton) {
		switch (currentButton.getId()) {
		case R.id.submit:
			username = userinput.getText().toString();
			password = passinput.getText().toString();
			sharedPrefernces();
			Toast.makeText(this, "Details are saved", 20).show();
			break;
		case R.id.exit:
			finish();
		}
	}
}

Run your project you will get the output as below:

Shows Login Page of activity

Figure 3 : Shows Login Page of activity

Shows Message displayed when user click on submit button

Figure 4: Shows Message displayed when user click on submit button

Listing 3: To check the saved data pull the xml file from emulator by navigating to below :

Go to DDMS>File Explorer>data>data>package_name>shared_prefs>selectfile
Showing DDMS panel.

Figure 5 : Showing DDMS panel.

Showing file Login Credentials.xml

Figure 6 : Showing file “Login Credentials.xml”

To pull out the file from emulator go to top right side of the panel there is button for this operation as show below :

Shows DDMS Position.

Figure 7 : Shows DDMS Position.

Pull the file from the device and save it to the desired location then open this file in any text editor(notepad etc) then you will able see your data that you have saved.

Saving file

Figure 8: Saving file

getInit() method : This method is user defined method for the fetching of id’s from xml file.

Listing 4: Explanation of code Above :

public void getInit() {
		submit = (Button) findViewById(R.id.submit);
		exit = (Button) findViewById(R.id.exit);
		userinput = (EditText) findViewById(R.id.userinput);
		passinput = (EditText) findViewById(R.id.passinput);
		submit.setOnClickListener(this);
		exit.setOnClickListener(this);
	}

sharedPrefernces() method() : This method is used to create the shared preferences and to write the contents in it by Editor.

public void sharedPrefernces() {

		sh_Pref = getSharedPreferences("Login Credentials", MODE_PRIVATE);
		toEdit = sh_Pref.edit();
		toEdit.putString("Username", username);
		toEdit.putString("Password", password);
		toEdit.commit();

	}

onClick(View currentButton) method : This is overridden method which is used to perform action when user click on the submit button and exit button. In this method when user click on the submit button then sharedPrefernces() method will be called which will create a new file named as “Login Credentials” and write the data inside it by take from username and password fields.

public void onClick(View currentButton) {
		switch (currentButton.getId()) {
		case R.id.submit:
			username = userinput.getText().toString();
			password = passinput.getText().toString();
			sharedPrefernces();
			Toast.makeText(this, "Details are saved", 20).show();
			break;
		case R.id.exit:
			finish();
		}

What is covered ?

  • SharedPreferences implementation.
  • How to use Editor to write data in Shared Preferences.
  • How to get file from an emulator.


Working in Software Development domain from 7 years now and is well equipped with programming languages like HTML, CSS, Java, PHP, .NET etc.

What did you think of this post?
Services
Know how to keep MrBool Online
SUPPORT US
SUPPORT US
With your help, we can keep providing free content and helping you to be a better professional
support us
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually � in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits � in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login