What is SharedPreferences and How to use sharedpreferences in android - SpartaCode

SpartaCode

Make your development faster and easier !

What is SharedPreferences and How to use sharedpreferences in android







What is SharedPreferences and why it is used ?


You can save and retrieve key, value pair data from Shared preferences.
SharedPreferences values will persist across user sessions. Data in shared preferences will be persistent even though user closes the application.You also need an editor to edit and save the changes in shared preferences.Use SharedPreferences to store data: booleans, floats, ints, longs, and strings.


To make you work simple i created a Utility file which can be used in any project you want 


Download following link and follow instructions :


Download SharedPreference.java



Instructions to use SharedPreference.java


Step 1 :   Copy paste downloaded file into your project

Step 2 :  Declaring SharedPreference static

Its most common that you may require sharedpreference very often in your project, So its better to declare it static into one class that executes first in your project and access it from anywhere you need to store data into sharedpreferences.

Copy this code in your first Activity :

public static SharedPreference sharedpreference;


Step 3 : How to use Shared Preference ?

To Store data :

Syntax :

<YourActivityName> . sharedpreference . setData("keyname","keyvalue");

Where, 

<YourActivityName>  : Activity which contains static sharedpreference object.

keyname : It is key that will be used to fetch data again anywhere in your project.

keyvalue : Its value associated with keyname you are passing to it.


Example :

MainActivity.sharedpreference.setData("UserId","28"); //Any value

To get data :

Syntax :

<YourActivityName> . sharedpreference . getData("keyname");


Example :

MainActivity.sharedpreference.getData("UserId"); //Returns 28 in my eg

Few more functions are available such as follows :


clearAll() : Clears all data into shared preferences.

remove("keyname") : Removes specific item from SharedPreference.


Thank you 
Please Subscribe to motivate me to make such simple tutorials. 


No comments:

Post a Comment

Get Amazing Traffic to your Site

Traffic Exchange

Post Bottom Ad

Responsive Ads Here