How to use Android SharedPreferences – Example

  • by
Android 4SharedPreferences

How to use Android SharedPreferences – Example

Android SharedPreferences can be used as an alternative to database, to save a small amount of information or data. They can be used to save preferences a user makes while using the application and also to store login credential. For example, while the user is signing-in into your application for very first time, you can save credentials or make boolean flag like isLoggedIn and save it in SharedPreferences value.

In this post I’ll be sharing a complete information regarding the usage of sharedpreferences which I know. I’ll try my best to make this as easy as possible. You’ll be able to understand completely the uses of Sharedpreferences in Android, just by reading this post. There’s no need to make new application,you can follow these steps in your present android application also.

Let’s consider two activities, ActivityOne.java and ActivityTwo.java. In first activity, the ActivityOne.java file there’s an EditText value which we need to store in sharedpreferences. Let’s say it’s the name of the User.

1. Creating SharedPreferences and Editing it :

Declaring the SharedPreference variable,

 SharedPreferences shp = getSharedPreferences("myPreferences", MODE_PRIVATE);

Here, “myPreferences” is the name of the SharedPreferences which will be shared accross different activities in application.

To edit the SharedPreferences values, SharedPreferences Editor is required.

 SharedPreferences.Editor shpEditor  = shp.edit();

Now, comes the main editing part. Here, string value of name of the user is going to be stored. So Editor must be storing a String variable.

shpEditor.putString("name","Jennifer");

Where, “name” is the key name of the string value and Jennifer is the name of the user or the actual string value to be stored.

And to commit the changes, use :

shpEditor.commit();

2. Retrieving the SharedPreferences values :

To retrieve a value from the sharedPreferences use :

  String userName = shp.getString("user","NO NAME");

Where, “user” is the key name of the string value stored in the sharedPreferences and “NO NAME” is the default value, in case something goes wrong, and the editor doesn’t saves the value.

3. To save different types of variables

Int value

To save and retrieve a int variable, use :

shpEditor.putInt("intValue",7);  //  putting the value
shpEditor.commit(); // saving the value
int number = shp.getInt("intValue",0); // retrieving the value of int

Float value

To save and retrieve a float variable value use :

shpEditor.putFloat("floatValue", 2.0f); // putting the value of float
shpEditor.commit(); // saving the value
shp.getFloat("floatValue",1.0f); // retrieving the value of float

Boolean value

To save and retrieve a Boolean variable value use :

shpEditor.putBoolean("boolValue", true); // putting the value of boolean
shpEditor.commit(); // saving the value
shp.getBoolean("boolValue",false); // retrieving the value of boolean variable

Okay now lets make an application using SharedPreferences in Android. I’m assuming that you
know how to make or create a new application in Android studio, if you are not familiar
you should checkout this link here.

The Application :

Create a new application in Android Studio and create two new layout resource file in res>layout folder named

  1. userinput.xml
  2. nextactivity.xml

Now edit both of then as following :

userinput.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical"
 android:padding="10dp">

<TextView
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_margin="5dp"
 android:text="Enter name :"
 android:textSize="20sp" />

<EditText
 android:id="@+id/edtname"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_margin="5dp"
 android:textSize="20sp" />

<TextView
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_margin="5dp"
 android:text="Enter fav number :"
 android:textSize="20sp" />

<EditText
 android:id="@+id/edtnum"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_margin="5dp"
 android:inputType="number"
 android:textSize="20sp" />

<TextView
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_margin="5dp"
 android:text="2+2=5, true/false"
 android:textSize="20sp" />

<EditText
 android:id="@+id/edtboolean"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_margin="5dp"
 android:textSize="20sp" />

<Button
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_margin="5dp"
 android:background="@color/colorPrimaryDark"
 android:text="Next"
 android:id="@+id/btnNext"
 android:textColor="#fff"
 android:textSize="16sp" />

<Button
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_margin="5dp"
 android:background="#e2e2e2"
 android:text="Clear"
 android:id="@+id/btnClear"
 android:textColor="@color/colorPrimaryDark"
 android:textSize="16sp" />

</LinearLayout>

The layout design contains three EditText boxes to enter name, favorite number and a true/false question. Two buttons to go to the next activity.

Android sharedPreferences 1

Now edit the other file as follows :

nextactivity.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical">

<TextView
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:id="@+id/txtResult"
 android:textColor="@color/colorPrimaryDark"
 android:textSize="25sp"
 android:text=""
 android:gravity="center_horizontal|center_vertical"
 />

</LinearLayout>

Here there’s only one TextView where we can show the value entered by the user which will be stored in shared preferences.

Android sharedpreferences 2

Now getting on to the code.

Create two new class files :

  1. UserInput.java
  2. NextActivity.java

First UserInput.java class file :

 

package parallel.sharedpreferences;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

/**
 * Created by acer on 12-Aug-16.
 */
public class UserInput extends AppCompatActivity {

Button btnNext, btnClear;
 EditText edtName, edtNum, edtboolean;
 SharedPreferences shp;
 SharedPreferences.Editor shpeditor;

@Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.userinput);
 btnNext = (Button) findViewById(R.id.btnNext);
 btnClear = (Button) findViewById(R.id.btnClear);
 edtName = (EditText) findViewById(R.id.edtname);
 edtNum = (EditText) findViewById(R.id.edtnum);
 edtboolean = (EditText) findViewById(R.id.edtboolean);

shp = this.getSharedPreferences("myPreferences", MODE_PRIVATE);

btnNext.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {
 shpeditor = shp.edit();
 shpeditor.putString("name", edtName.getText().toString());
 int num = Integer.parseInt(edtNum.getText().toString());
 shpeditor.putInt("num", num);
 Boolean b = Boolean.parseBoolean(edtboolean.getText().toString());
 shpeditor.putBoolean("bool", b);
 shpeditor.commit();
 Intent i = new Intent(UserInput.this,NextActivity.class);
 startActivity(i);
 }
 });
 }
}

Over here, I’m first declaring the sharedpreferences and then storing the values of the string, int and boolean in the sharedpreferences using the editor.commit(). And passing the activity to other activity using Intent.

And the second class file, NextActivity.java:

 

package parallel.sharedpreferences;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

/**
 * Created by acer on 12-Aug-16.
 */
public class NextActivity extends AppCompatActivity {

TextView txtResult;
 SharedPreferences shp;

@Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.nextactivity);
 txtResult = (TextView) findViewById(R.id.txtResult);
 shp = this.getSharedPreferences("myPreferences", MODE_PRIVATE);

String name = shp.getString("name", "0.00");
 String num = String.valueOf(shp.getInt("num", 0));
 Boolean b = shp.getBoolean("bool", false);

txtResult.setText("Hi " + name + ", your favourite number is " + num + ". And you gave answer as " + String.valueOf(b));

}
}

 

And the AndroidManifest.xml:

 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="parallel.sharedpreferences">

<application
 android:allowBackup="true"
 android:icon="@mipmap/ic_launcher"
 android:label="@string/app_name"
 android:supportsRtl="true"
 android:theme="@style/AppTheme">
 <activity
 android:name=".UserInput"
 android:label="@string/app_name"
 android:screenOrientation="portrait"
 android:theme="@style/AppTheme.NoActionBar">
 <intent-filter>
 <action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
 </intent-filter>
 </activity>
 <activity
 android:name=".NextActivity"
 android:label="@string/app_name"
 android:screenOrientation="portrait"
 android:theme="@style/AppTheme.NoActionBar"/>

</application>

</manifest>

 

If you have any doubts or queries, please let me know in the comment section below, I’ll try to help you out. If you find something wrongs or errors in my code please let me know, I’ll openly accept the mistakes if any.

And lastly please opt for newsletters and like my social networks pages for regular updates.

Github Link


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.