Thursday, 22 October 2015

Shared Preferences in Android : Saving and retrieving stored data in sharedPreferences

       Their are several ways to store data in your android device, mainly using SQlite Database and shared Preferences. The data's are stored in shared Preferences key n value pair.

       Each key points to its value. You could add, delete or update sharedPreferences  by using the pointing key. In this tutorial you're gonna learn how to use shared Preference in android.

  In order to use shared Preference in android you have to Create and initialize sharedPreferences:
 SharedsharedPreferenceserences sharedPreferences = getApplicationContext().getSharedsharedPreferenceserences("userSharedPreferences", MODE_PRIVATE);   
   xEditor xEditor = sharedPreferences.edit();  

Inserting data as key n value form:
 xEditor.putBoolean("key_x_1", true);      // Store boolean : true or false  
   xEditor.putInt("key_x_2", "int_value");    // Store integer  
   xEditor.putFloat("key_x_3", "float_value");  // Store float  
   xEditor.putLong("key_x_4", "long_value");   // Store long  
   xEditor.putString("key_x_5", "string_value"); // Store string  
   // save changes  
   xEditor.commit(); // saving changes  

Retrieving / Fetching data stored in sharedPreferences:
*If the key doesn't posses any_value then the second parameter is saved as a new falue for the respective key!
 sharedPreferences.getBoolean("key_x_1", null);     // fetching boolean  
   sharedPreferences.getInt("key_x_2", null);       // fetching Integer  
   sharedPreferences.getFloat("key_x_3", null);      // fetching Float  
   sharedPreferences.getLong("key_x_4", null);      // fetching Long  
   sharedPreferences.getString("key_x_5", null);     // fetching String  

Removing / Deleting Key and its Value from sharedPreferences:
 xEditor.remove("key_x_3"); // will delete key key_x_3  
   xEditor.remove("key_x_4"); // will delete key key_x_4  
   // Save the changes in SharedsharedPreferenceserences  
   xEditor.commit(); // commit changes  

Clearing / deleting all entries from sharedPreferences:
 xEditor.clear();  
    xEditor.commit(); // commit changes  


No comments:

Post a Comment