Tuesday, 2 April 2013

Shared Preferences in Android

In android one of the way using which you can store data is using shared preferences. You can also store data in global variable and use it but in that Global data will lost when user close the application. While with Shared preferences data will be persistent even if user close the application.

   For example for login form generally all login form have concept for remember password. In android you acieve this type of functionality by using SharedPreferences.

Example :-
    ->  How to Initialization 

         SharedPreferences _mypref = getApplicationContext().getSharedPreferences("mypref", 0);    <--- 0 - for private

         Editor editor = _mypref.edit();
   -> How to store data in shared preferences

Storing boolean - true/false

                               editor.putBoolean("key_name", true);  
 Storing string

                               editor.putString("key_name", "string value");

Storing integer
                               editor.putInt("key_name", "int value");    

Storing float
                               editor.putFloat("key_name", "float value");      

 Storing long 

                               editor.putLong("key_name", "long value");

commit changes


   -> How to Retrieving Data

getting String
                               _mypref .getString("key_name", null);

getting Integer
                               _mypref .getInt("key_name", null);         

 getting Float
                               _mypref .getFloat("key_name", null);  

getting Long
                               _mypref .getLong("key_name", null);    

getting boolean
                               _mypref.getBoolean("key_name", null);    

  -> How to remove Data


  -> How to Clear all Data 


No comments:

Post a Comment