Android provides many ways of storing data of an application. One of this way is called Shared Preferences. Shared Preferences allow you to save and retrieve data in the form of key,value pair.
In order to use shared preferences , you have to call a method getSharedPreferences() that returns a SharedPreference instance poiting to the file that contains the values of preferences.
1 |
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE); |
The first parameter is the key and the second parameter is the MODE. Apart from private there are other modes availaible that are listed below:
Mode | Description |
---|---|
MODE_APPEND | This will append the new preferences with the already existing preferences. |
MODE_ENABLE_WRITE_AHEAD_LOGGING | Database open flag. When it is set , it would enable write ahead logging by default. |
MODE_MULTI_PROCESS | This method will check for modification of preferences even if the sharedpreference instance has already been loaded. |
MODE_PRIVATE | By setting this mode , the file can only be accessed using calling application. |
MODE_WORLD_READABLE | This mode allow other application to read the preferences. |
MODE_WORLD_WRITEABL | This mode allow other application to write the preferences. |
You can save something in the sharedpreferences by using SharedPreferences.Editor class. You will call the edit method of SharedPreference instance and will recieve it in an editor object. Its syntax is:
1 2 3 |
Editor editor = sharedpreferences.edit(); editor.putString("key", "value"); editor.commit(); |
Apart from the putString method , there are methods availaible in the editor class that allows manipulation of data inside shared preferences. They are listed as follows:
Method | Description |
---|---|
apply() | It is an abstract method. It will commit your changes back from editor to the sharedPreference object you are calling. |
clear() | It will remove all values from the editor. |
remove(String key) | It will remove the value whose key has been passed as a parameter. |
putLong(String key, long value) | It will save a long value in a preference editor. |
putInt(String key, int value) | It will save a integer value in a preference editor. |
putFloat(String key, float value) | It will save a float value in a preference editor. |
In this example i will be demonstrating how to work on SharedPreferences for storing values in it and fetching again the values.
Let’s get start by creating a project in Eclipse IDE.
1. Create a new project in Eclipse by navigating to File ⇒ New Android ⇒ Application Project and fill required details. (I kept my main activity name as MainActivity.java)
2. Open your your AndroidManifest.xml file and make your “MainActivity” as Launcher activity.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.sharedpreference_demo" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="22" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> |
3. Create a layout file for MainActivtiy.java under res ⇒ layout folder. I named the layout file as activity_main.xml.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#ffffff" android:orientation="vertical" android:padding="5dp" > <EditText android:id="@+id/username" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:hint="@string/name" android:inputType="text" android:padding="10dp" android:singleLine="true" /> <EditText android:id="@+id/emailid" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:hint="@string/email" android:inputType="textEmailAddress" android:padding="10dp" android:singleLine="true" /> <EditText android:id="@+id/phoneno" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:hint="@string/phone" android:inputType="phone" android:padding="10dp" android:singleLine="true" /> <Button android:id="@+id/save" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:background="#ff6600" android:padding="10dp" android:text="@string/save" android:textColor="#ffffff" android:textSize="18sp" /> <Button android:id="@+id/show" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:background="#ff6600" android:padding="10dp" android:text="@string/show" android:textColor="#ffffff" android:textSize="18sp" /> <TextView android:id="@+id/saved_data" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:padding="10dp" android:textSize="18sp" android:visibility="gone" /> <Button android:id="@+id/delete" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:background="#ff6600" android:padding="10dp" android:text="@string/delete" android:textColor="#ffffff" android:textSize="18sp" android:visibility="gone" /> </LinearLayout> |
4. Add the following code in MainActivity.java activity. In this following code we use editor to store data in shared preferences on button click and fetch data from shared preferences and finally deleting/clearing shared preferences.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 |
package com.sharedpreference_demo; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends ActionBarActivity implements OnClickListener { EditText name, email, phone; Button save, show, delete; TextView show_saved_data; //Shared Preference for storing data SharedPreferences preferences; //Editor to edit shared preference Editor editor; //String variables for shared preference private static final String shared_preferences = "shared_preferences"; private static final String stored_name = "name"; private static final String stored_email = "email"; private static final String stored_phone = "phone"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Finding all views id name = (EditText) findViewById(R.id.username); email = (EditText) findViewById(R.id.emailid); phone = (EditText) findViewById(R.id.phoneno); save = (Button) findViewById(R.id.save); show = (Button) findViewById(R.id.show); delete = (Button) findViewById(R.id.delete); show_saved_data = (TextView) findViewById(R.id.saved_data); //Getting shared preference preferences = getSharedPreferences(shared_preferences, Context.MODE_PRIVATE); //Initializing editor to edit preference editor = preferences.edit(); //Implementing click listener on all buttons that are used save.setOnClickListener(this); show.setOnClickListener(this); delete.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.save: //Getting edittext texts into string variables String getName = name.getText().toString(); String getEmail = email.getText().toString(); String getPhone = phone.getText().toString(); //Checking if all text fields are filled or empty if (TextUtils.isEmpty(getName) || TextUtils.isEmpty(getEmail) || TextUtils.isEmpty(getPhone)) { //If all text fields are not filled an toast is shown Toast.makeText(MainActivity.this, "Please Fill all Fields.", Toast.LENGTH_SHORT).show(); } else { //else text fields data is stored in shared preference editor.putString(stored_name, getName); editor.putString(stored_email, getEmail); editor.putString(stored_phone, getPhone); //After storing data commit the editor to save data editor.commit(); //And clear the edittext fields name.setText(""); email.setText(""); phone.setText(""); //Toast is shown to show that data is saved Toast.makeText(MainActivity.this, "Data Saved Successfully.", Toast.LENGTH_SHORT).show(); } break; case R.id.show: //Check if preference contains stored data or not if (preferences.contains(stored_name) && preferences.contains(stored_email) && preferences.contains(stored_phone)) { //If data is stored get the data and display on textView String getSavedName = preferences.getString(stored_name, null); String getSavedEmail = preferences .getString(stored_email, null); String getSavedPhone = preferences .getString(stored_phone, null); show_saved_data.setText("Full Name : " + getSavedName + "n" + "Email Id : " + getSavedEmail + "n" + "Phone No. : " + getSavedPhone); //Showing delete button that is invisible till delete.setVisibility(View.VISIBLE); } else { //Display the data if data is not saved show_saved_data .setText("There is no data in Shared Prefrences."); } //Showing textView on show button click show_saved_data.setVisibility(View.VISIBLE); break; case R.id.delete: //Check if data contains in shared preference if (preferences.contains(stored_name) && preferences.contains(stored_email) && preferences.contains(stored_phone)) { //If contains clear the editor and commit it editor.clear(); editor.commit(); } else { //If not present any data then toast is displayed Toast.makeText(MainActivity.this, "Already Cleared.", Toast.LENGTH_SHORT).show(); } // Both textView and delete button is visible show_saved_data.setVisibility(View.GONE); delete.setVisibility(View.GONE); break; } } } |
5. Now, run the application and you will get the output as shown in video.
Thanks. 🙂
Subscribe to us and get the latest news.