Android – Introduction to SharedPreferences
Being able to save or persist data within your application is a fundamental skill. It enables your users to save their work, remember their preferences, store all types of files for reuse, and more.
This tutorial introduces you to one of the different ways in which you can persist data in your application : SharedPreferences.
Next tutorial is about User session management with SharedPreferences, and coming tutorials will be about other possibilities for data persistance on Android such as file storage and SQLite.
So, let’s get first started wih SharedPreferences !
SharedPreferences allows you to save and retrieve key, value pair data. You need to fetch your app’s shared preferences, then start saving, retreiving, editing or clearing your data.
Initialization
Application shared preferences can be fetched using getSharedPreferences() method. You also need an editor to edit and save the changes in shared preferences :
SharedPreferences prefs =getApplicationContext().getSharedPreferences("AppPref", 0); // 0 for private mode Editor editor = prefs.edit();
Storing data
You will use editor to save the data into shared preferences . All primitive data types like booleans, floats, ints, longs, and strings are supported. Then, you must call editor.commit() in order to save changes to shared preferences.
editor.putBoolean("key_name", true); // Storing boolean - true/false editor.putString("key_name", "string value"); // Storing string editor.putInt("key_name", "int value"); // Storing integer editor.putFloat("key_name", "float value"); // Storing float editor.putLong("key_name", "long value"); // Storing long editor.commit(); // commit changes;
Retrieving data
To retrieve data from saved preferences you need to call getString() (for getting a string) method on SharedPrefrences object .
// returns stored preference value // If value is not present return second param value - In this case null prefs.getString("key_name", null); // getting String prefs.getInt("key_name", null); // getting Integer prefs.getFloat("key_name", null); // getting Float prefs.getLong("key_name", null); // getting Long prefs.getBoolean("key_name", null); // getting boolean editor.commit(); // commit changes;
Editing data
To edit any data, save it using the same key that you used earlier. It will overwrite new data on the previous.
Clearing or deleting data
If you want to delete from shared preferences you can call remove(“key_name”) to delete that particular value. If you want to delete all the data, call clear() .
editor.remove("name") // deletes key name editor.remove("email") // deletes key email
editor.clear(); // removes all data editor.commit();
That’s all about shared preferences. You can find below a basic example to help you understand how it is used in an Android app.
SharedPreferences example
Create a project with package named sharedpref.
In your 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" tools:context=".MainActivity" android:orientation="vertical" android:layout_marginLeft="15dp" android:layout_marginRight="15dp" android:layout_marginTop="15dp" android:layout_marginBottom="15dp"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/text"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Save" android:id="@+id/saveButton" android:onClick="buttonAction"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Remove" android:id="@+id/removeButton" android:onClick="buttonAction"/> </LinearLayout>
Then, in MainActivity.java add the following :
package com.example.amal.sharedpref; import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends Activity { Button saveButton,removeButton; EditText text; SharedPreferences sp; SharedPreferences.Editor editor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); saveButton=(Button)findViewById(R.id.saveButton); removeButton=(Button)findViewById(R.id.removeButton); text=(EditText)findViewById(R.id.text); sp=getSharedPreferences("TheCrazyProgrammer",MODE_PRIVATE); editor=sp.edit(); if(sp.contains("name")){ text.setText(sp.getString("name","null")); } } public void buttonAction(View view) { if(view.getId()==R.id.saveButton){ editor.putString("name",text.getText().toString()); editor.commit(); Toast.makeText(getApplicationContext(),"Preferences Saved",Toast.LENGTH_LONG).show(); } if(view.getId()==R.id.removeButton){ editor.clear(); editor.commit(); Toast.makeText(getApplicationContext(),"Preferences Removed",Toast.LENGTH_LONG).show(); } } }
Now run the project, and save some text using the save button.
Close the application and run it again. You will see that the textbox display the data you have saved earlier. This proves that data is not lost even after closing the application.
That’s what SharedPreferences is for ! It’s wideley used for session management in Android apps.
You can download the source code from here. Let me know if you have any questions .
If not jump to next tutorial !
tanks
Anytime.
Hi , I do consider this is an excellent blog. I stumbled upon it on Yahoo , I
shall return once again.
Great post. I ‘m confronting a couple of these problems.