Answers for "shared preferences android example"

2

Shared preferences android example

Create SharedPreferences
    SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE); 
    Editor editor = pref.edit();

Storing data as KEY/VALUE pair
    editor.putBoolean("key_name1", true);           // Saving boolean - true/false
    editor.putInt("key_name2", "int value");        // Saving integer
    editor.putFloat("key_name3", "float value");    // Saving float
    editor.putLong("key_name4", "long value");      // Saving long
    editor.putString("key_name5", "string value");  // Saving string

    // Save the changes in SharedPreferences
    editor.apply(); // commit changes


Get SharedPreferences data
    // If value for key not exist then return second param value - In this case null
    boolean userFirstLogin= pref.getBoolean("key_name1", true);  // getting boolean
    int pageNumber=pref.getInt("key_name2", 0);             // getting Integer
    float amount=pref.getFloat("key_name3", null);          // getting Float
    long distance=pref.getLong("key_name4", null);          // getting Long
    String email=pref.getString("key_name5", null);         // getting String


Deleting Key value from SharedPreferences
    editor.remove("key_name3"); // will delete key key_name3
    editor.remove("key_name4"); // will delete key key_name4
    // Save the changes in SharedPreferences
    editor.apply(); // commit changes

Clear all data from SharedPreferences
   editor.clear();
   editor.apply(); // commit changes
Posted by: Guest on November-15-2021
4

android sharedpreferences

SharedPreferences sharedPref = getSharedPreferences("name", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("key", "Value");
editor.commit();
Posted by: Guest on November-07-2020
-1

store data in sharedpreferences android

// MY_PREFS_NAME - a static String variable like: 
//public static final String MY_PREFS_NAME = "MyPrefsFile";
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
 editor.putString("name", "Elena");
 editor.putInt("idName", 12);
 editor.apply();
Posted by: Guest on November-04-2020
0

set preference value android

boolean committed = PreferenceManager.getDefaultSharedPreferences(yourContext).edit().putBoolean(key, mValue).commit();
//you can also use putInt, putFloat, putLong, putString, putStringSet and change the value of mValue
//committed is true if everything went alright, false if there was an error
Posted by: Guest on March-16-2020

Code answers related to "shared preferences android example"

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language