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

    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 518
    Comment on it

    Android provides some features to store and retrieve data of an application. SharedPreferences is one of the simple and easy way among them.We save data in key, value pair.

    We have to call getSharedPreferences(), It returns the SharedPrefrence instance thats point the file containing the value.

    SharedPreferences userPreferences=context.getSharedPreferences(EMPLOYEES_INF, Context.MODE_PRIVATE);
    1st parameter is the key and 2nd is the MODE.

    There are other modes also:

    *MODE_APPEND: It appends new preferences to already existed preferences.

    *MODE_PRIVATE: Its the default mode,It means the file accessed by only the calling application.

    *MODE_WORLD_READABLE: allow all applications to have read access to the file.

    *MODE_WORLD_WRITEABLE: allow all applications to have write access to the file.

    We save any value by using SharedPrefrences.Editor class. We have to call the edit() method of Editor class.

    Editor editor = userPreferences.edit();
    editor.putString("key1", "value1");
    editor.putString("key2", "value2");
    editor.putString("key3", "value3");

    We can get these value like this :

    SharedPreferences userPreferences = this.getSharedPreferences(SharedPreferenceManager.EMPLOYEES_INF, 0);
    String value1 =userPreferences.getString("key1", "");
    String value2 = userPreferences.getString("key1", "");

    Methods available in Editor class:

    * remove(String key): It removes the value according to the passed key.

    * clear(): It remove all values from the specific editor.

    * putLong(String key, long value): It saves a long value.

    * putInt(String key, int value): It saves an integer value.

    * putFloat(String key, float value): It saves a float value.

 0 Comment(s)

Sign In

Sign up using

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: