Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Shared Preferences in Android

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 333
    Comment on it

    Android provide many ways to store or save data of an application, one of the method is using Shared Preferences. Shared Preferences are used to store and retrieve primitive data information(such as int, boolean, and String). The data is stored in a Key:Value pair. The value is retrieve using the key.

    Syntax for using shared preferences:

    string PREFS_NAME="credential";
    SharedPreferences sharedpreferences = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);    
    

    The first parameter is the key (this key is used to identify the preference)and the second parameter is the MODE. There are several other mode like MODE_APPEND,MODE_WORLD_READABLE etc.

    • To write/store values in shared preferences you need to use SharedPreferences.Editor class object.
    • The edit() function of SharedPreferences called to get Editor.
    • To add/change values putBoolean(), putString() etc methods are used.
    • Save the new values into SharedPreferences usingcommit() method.

    The Syntax is:

    {
          SharedPreferences sharedpreferences = getSharedPreferences(PREFS_NAME, 0);
          SharedPreferences.Editor editor = sharedpreferences.edit();
          editor.putString("username", "pankaj");
          editor.putString("password", "12345");
          editor.commit();
    }

    To read values from SharedPreferences getString(),getBollean() methods are used.

    Syntax to get values:

    {
          SharedPreferences sharedpreferences = getSharedPreferences(PREFS_NAME, 0);
          string username = sharedpreferences.getInt("username", null);
          string password = sharedpreferences.getInt("password", null);
    }
    

    The "null " is provided so that if no value is obtained then null value is assigned to username and password variables.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: