Here you will get android SharedPreferences example.
SharedPreferences in android is used to save data which is available across entire application and the data persists even after the application is closed. It is widely used for session management in android applications. SharedPreferences uses key-value pair to save and retrieve data.
Save Data
First of all we have to get SharedPreferences instance by calling getSharedPreferences() method. It can be done in following way.
SharedPreferences sp = getSharedPreferences(YourPreferencesKey,Mode);
Here first parameter is the user define key in string format and second parameter is the mode. The various modes that we can use are:
- MODE_APPEND
- MODE_ENABLE_WRITE_AHEAD_LOGGING
- MODE_MULTI_PROCESS
- MODE_PRIVATE
- MODE_WORLD_READABLE
- MODE_WORLD_WRITEABLE
Next step is to get SharedPreferences.Editor class object by calling edit() method using SharedPreferences object. It can be done in following way.
SharedPreferences.Editor editor = sp.edit();
After that call putString() method using Editor object.
editor.putString(key,value);
Here both key and value are in string format. There are some other methods like putBoolean(), putInt(), putLong() and putFloat() to save boolean, integer, long and float values respectively.
Finally call commit() method to save the changes.
editor.commit();
Retrieve Data
First get instance of SharedPreferences by calling getSharedPreferences() method. After that use getString() method to fetch the data. It can be done in following way.
SharedPreferences sp = getSharedPreferences(YourPreferencesKey,Mode); sp.getString(key,default_value);
When there is no data associated with given key then the default value is returned. There are some other methods to fetch data, like getBoolean(), getInt(), getFloat() and getLong().
We can use contains() method to check whether SharedPreferences contain some value or not.
if(sp.contains(key)) { //perform some task here }
Modify Data
To modify any data, save the data using the same key that you used earlier. It will overwrite new data on previous data.
Delete Data
Use remove() method to delete a data associated with particular key. You can use clear() method to delete all the data present in SharedPreferences. It can be done in following way.
editor.remove(key); //remove single data editor.clear(); //remove all data editor.commit();
You must always call commit() method after doing any changes in data.
Below I have shared one simple example that will show how SharedPreferences is used in android.
Android SharedPreferences Example
Create a project with package name thecrazyprogrammer.androidexample. Now paste following code in respective files.
activity_main.xml
<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>
MainActivity.java
package thecrazyprogrammer.androidexample; 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(); } } }
Run project and save some data using textbox and save button. Now 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. You can use remove button to delete the data.
Comment below if you have any doubts regarding above android SharedPreferences example.
Happy Coding!! 🙂 🙂
Thanks for sharing helpful example
keep going 🙂