How to use SharedPreferences in Android to store,

2018-12-30 22:39发布

I want to store a time value and need to retrieve and edit it. How can I use SharedPreferences to do this?

30条回答
泪湿衣
2楼-- · 2018-12-30 22:43

Basic idea of SharedPreferences is to store things on XML file.

  1. Declare your xml file path.(if you don't have this file, Android will create it. If you have this file, Android will access it.)

    SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
    
  2. Write value to Shared Preferences

    prefs.edit().putLong("preference_file_key", 1010101).apply();
    

    the preference_file_key is the name of shared preference files. And the 1010101 is the value you need to store.

    apply() at last is to save the changes. If you get error from apply(), change it to commit(). So this alternative sentence is

    prefs.edit().putLong("preference_file_key", 1010101).commit();
    
  3. Read from Shared Preferences

    SharedPreferences sp = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
    long lsp = sp.getLong("preference_file_key", -1);
    

    lsp will be -1 if preference_file_key has no value. If 'preference_file_key' has a value, it will return the value of this.

The whole code for writing is

    SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);    // Declare xml file
    prefs.edit().putLong("preference_file_key", 1010101).apply();    // Write the value to key.

The code for reading is

    SharedPreferences sf = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);    // Declare xml file
    long lsp = sp.getLong("preference_file_key", -1);    // Read the key and store in lsp
查看更多
流年柔荑漫光年
3楼-- · 2018-12-30 22:43

I wanted to add here that most of the snippets for this question will have something like MODE_PRIVATE when using SharedPreferences. Well, MODE_PRIVATE means that whatever you write into this shared preference can only be read by your application only.

Whatever key you pass to getSharedPreferences() method, android creates a file with that name and stores the preference data into it. Also remember that getSharedPreferences() is supposed to be used when you intend to have multiple preference files for your application. If you intend to use single preference file and store all key-value pairs into it then use the getSharedPreference() method. Its weird why everyone (including myself) simply uses getSharedPreferences() flavor without even understanding the difference between the above two.

The following video tutorial should help https://www.youtube.com/watch?v=2PcAQ1NBy98

查看更多
ら面具成の殇う
4楼-- · 2018-12-30 22:44

To obtain shared preferences, use the following method In your activity:

SharedPreferences prefs = this.getSharedPreferences(
      "com.example.app", Context.MODE_PRIVATE);

To read preferences:

String dateTimeKey = "com.example.app.datetime";

// use a default value using new Date()
long l = prefs.getLong(dateTimeKey, new Date().getTime()); 

To edit and save preferences

Date dt = getSomeDate();
prefs.edit().putLong(dateTimeKey, dt.getTime()).apply();

The android sdk's sample directory contains an example of retrieving and storing shared preferences. Its located in the:

<android-sdk-home>/samples/android-<platformversion>/ApiDemos directory

Edit==>

I noticed, it is important to write difference between commit() and apply() here as well.

commit() return true if value saved successfully otherwise false. It save values to SharedPreferences synchronously.

apply() was added in 2.3 and doesn't return any value either on success or failure. It saves values to SharedPreferences immediately but starts an asynchronous commit. More detail is here.

查看更多
旧时光的记忆
5楼-- · 2018-12-30 22:45

Singleton Shared Preferences Class. it may help for others in future.

  import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;

public class SharedPref
{
    private static SharedPreferences mSharedPref;
    public static final String NAME = "NAME";
    public static final String AGE = "AGE";
    public static final String IS_SELECT = "IS_SELECT";

    private SharedPref()
    {

    }

    public static void init(Context context)
    {
        if(mSharedPref == null)
            mSharedPref = context.getSharedPreferences(context.getPackageName(), Activity.MODE_PRIVATE);
    }

    public static String read(String key, String defValue) {
        return mSharedPref.getString(key, defValue);
    }

    public static void write(String key, String value) {
        SharedPreferences.Editor prefsEditor = mSharedPref.edit();
        prefsEditor.putString(key, value);
        prefsEditor.commit();
    }

    public static boolean read(String key, boolean defValue) {
        return mSharedPref.getBoolean(key, defValue);
    }

    public static void write(String key, boolean value) {
        SharedPreferences.Editor prefsEditor = mSharedPref.edit();
        prefsEditor.putBoolean(key, value);
        prefsEditor.commit();
    }

    public static Integer read(String key, int defValue) {
        return mSharedPref.getInt(key, defValue);
    }

    public static void write(String key, Integer value) {
        SharedPreferences.Editor prefsEditor = mSharedPref.edit();
        prefsEditor.putInt(key, value).commit();
    }
}

Simply call SharedPref.init() on MainActivity once

SharedPref.init(getApplicationContext());

To Write data

SharedPref.write(SharedPref.NAME, "XXXX");//save string in shared preference.
SharedPref.write(SharedPref.AGE, 25);//save int in shared preference.
SharedPref.write(SharedPref.IS_SELECT, true);//save boolean in shared preference.

To Read Data

String name = SharedPref.read(SharedPref.NAME, null);//read string in shared preference.
int age = SharedPref.read(SharedPref.AGE, 0);//read int in shared preference.
boolean isSelect = SharedPref.read(SharedPref.IS_SELECT, false);//read boolean in shared preference.
查看更多
无色无味的生活
6楼-- · 2018-12-30 22:46

Here i have created an Helper class to use preferences in android.

This is the helper class:

public class PrefsUtil {

public static SharedPreferences getPreference() {
    return PreferenceManager.getDefaultSharedPreferences(Applicatoin.getAppContext());
}

public static void putBoolean(String key, boolean value) {
    getPreference().edit().putBoolean(key, value)
            .apply();
}

public static boolean getBoolean(String key) {
    return getPreference().getBoolean(key, false);
}

public static void putInt(String key, int value) {

    getPreference().edit().putInt(key, value).apply();

}

public static void delKey(String key) {

    getPreference().edit().remove(key).apply();

}

}
查看更多
高级女魔头
7楼-- · 2018-12-30 22:49

Setting values in Preference:

// 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.commit();

Retrieve data from preference:

SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); 
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
  String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
  int idName = prefs.getInt("idName", 0); //0 is the default value.
}

more info:

Using Shared Preferences

Shared Preferences

查看更多
登录 后发表回答