如何在Android中使用SharedReferences来存储、获取和编辑值

如何在Android中使用SharedReferences来存储、获取和编辑值,android,sharedpreferences,Android,Sharedpreferences,我想存储一个时间值,需要检索和编辑它。如何使用SharedReferences执行此操作?编辑SharedReference中的数据 SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit(); editor.putString("text", mSaved.getText().toString()); editor.putInt("selection-start", mSaved.getSelectionSt

我想存储一个时间值,需要检索和编辑它。如何使用
SharedReferences
执行此操作?

编辑
SharedReference
中的数据

 SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
 editor.putString("text", mSaved.getText().toString());
 editor.putInt("selection-start", mSaved.getSelectionStart());
 editor.putInt("selection-end", mSaved.getSelectionEnd());
 editor.apply();
SharedPreferences prefs = getPreferences(MODE_PRIVATE); 
String restoredText = prefs.getString("text", null);
if (restoredText != null) 
{
  //mSaved.setText(restoredText, TextView.BufferType.EDITABLE);
  int selectionStart = prefs.getInt("selection-start", -1);
  int selectionEnd = prefs.getInt("selection-end", -1);
  /*if (selectionStart != -1 && selectionEnd != -1)
  {
     mSaved.setSelection(selectionStart, selectionEnd);
  }*/
}
SharedReference

 SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
 editor.putString("text", mSaved.getText().toString());
 editor.putInt("selection-start", mSaved.getSelectionStart());
 editor.putInt("selection-end", mSaved.getSelectionEnd());
 editor.apply();
SharedPreferences prefs = getPreferences(MODE_PRIVATE); 
String restoredText = prefs.getString("text", null);
if (restoredText != null) 
{
  //mSaved.setText(restoredText, TextView.BufferType.EDITABLE);
  int selectionStart = prefs.getInt("selection-start", -1);
  int selectionEnd = prefs.getInt("selection-end", -1);
  /*if (selectionStart != -1 && selectionEnd != -1)
  {
     mSaved.setSelection(selectionStart, selectionEnd);
  }*/
}
编辑


我从API演示示例中获取了这个片段。它有一个
EditText
框。在此
上下文中
不是必需的。我对此进行了评论。

要获得共享首选项,请使用以下方法 在您的活动中:

SharedPreferences prefs = this.getSharedPreferences(
      "com.example.app", Context.MODE_PRIVATE);
要阅读首选项,请执行以下操作:

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

// use a default value using new Date()
long l = prefs.getLong(dateTimeKey, new Date().getTime()); 
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Name","Harneet");
editor.apply();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = preferences.getString("Name", "");
if(!name.equalsIgnoreCase(""))
{
    name = name + "  Sethi";  /* Edit the value here*/
}
public String getPreferences(Context context, String prefKey) {
  SharedPreferences sharedPreferences = PreferenceManager
 .getDefaultSharedPreferences(context);
 return sharedPreferences.getString(prefKey, "");
}
import android.content.Context;
import android.content.SharedPreferences;

/**
 * Created by mete_ on 23.12.2016.
 */
public class HelperSharedPref {

Context mContext;

public HelperSharedPref(Context mContext) {
    this.mContext = mContext;
}

/**
 *
 * @param key Constant RC
 * @param value Only String, Integer, Long, Float, Boolean types
 */
public void saveToSharedPref(String key, Object value) throws Exception {
    SharedPreferences.Editor editor = mContext.getSharedPreferences(key, Context.MODE_PRIVATE).edit();
    if (value instanceof String) {
        editor.putString(key, (String) value);
    } else if (value instanceof Integer) {
        editor.putInt(key, (Integer) value);
    } else if (value instanceof Long) {
        editor.putLong(key, (Long) value);
    } else if (value instanceof Float) {
        editor.putFloat(key, (Float) value);
    } else if (value instanceof Boolean) {
        editor.putBoolean(key, (Boolean) value);
    } else {
        throw new Exception("Unacceptable object type");
    }

    editor.commit();
}

/**
 * Return String
 * @param key
 * @return null default is null
 */
public String loadStringFromSharedPref(String key) throws Exception {
    SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
    String restoredText = prefs.getString(key, null);

    return restoredText;
}

/**
 * Return int
 * @param key
 * @return null default is -1
 */
public Integer loadIntegerFromSharedPref(String key) throws Exception {
    SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
    Integer restoredText = prefs.getInt(key, -1);

    return restoredText;
}

/**
 * Return float
 * @param key
 * @return null default is -1
 */
public Float loadFloatFromSharedPref(String key) throws Exception {
    SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
    Float restoredText = prefs.getFloat(key, -1);

    return restoredText;
}

/**
 * Return long
 * @param key
 * @return null default is -1
 */
public Long loadLongFromSharedPref(String key) throws Exception {
    SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
    Long restoredText = prefs.getLong(key, -1);

    return restoredText;
}

/**
 * Return boolean
 * @param key
 * @return null default is false
 */
public Boolean loadBooleanFromSharedPref(String key) throws Exception {
    SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
    Boolean restoredText = prefs.getBoolean(key, false);

    return restoredText;
}

}
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sp.edit();
editor.putString("Name","Jayesh");
editor.commit();
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String name = sp.getString("Name", "");
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sp.edit();
editor.putString("Name","Jayesh");
editor.commit();
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String name = sp.getString("Name", ""); // Second parameter is the default value.
编辑和保存首选项的步骤

Date dt = getSomeDate();
prefs.edit().putLong(dateTimeKey, dt.getTime()).apply();
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.commit();
prefs.edit().putLong("preference_file_key", 1010101).apply();
SharedPreferences sp = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
long lsp = sp.getLong("preference_file_key", -1);
android sdk的示例目录包含检索和存储共享首选项的示例。其位于:

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

最简单的方法:

要保存:

getPreferences(MODE_PRIVATE).edit().putString("Name of variable",value).commit();
要检索:

your_variable = getPreferences(MODE_PRIVATE).getString("Name of variable",default value);

要在共享首选项中存储值,请执行以下操作:

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

// use a default value using new Date()
long l = prefs.getLong(dateTimeKey, new Date().getTime()); 
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Name","Harneet");
editor.apply();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = preferences.getString("Name", "");
if(!name.equalsIgnoreCase(""))
{
    name = name + "  Sethi";  /* Edit the value here*/
}
public String getPreferences(Context context, String prefKey) {
  SharedPreferences sharedPreferences = PreferenceManager
 .getDefaultSharedPreferences(context);
 return sharedPreferences.getString(prefKey, "");
}
import android.content.Context;
import android.content.SharedPreferences;

/**
 * Created by mete_ on 23.12.2016.
 */
public class HelperSharedPref {

Context mContext;

public HelperSharedPref(Context mContext) {
    this.mContext = mContext;
}

/**
 *
 * @param key Constant RC
 * @param value Only String, Integer, Long, Float, Boolean types
 */
public void saveToSharedPref(String key, Object value) throws Exception {
    SharedPreferences.Editor editor = mContext.getSharedPreferences(key, Context.MODE_PRIVATE).edit();
    if (value instanceof String) {
        editor.putString(key, (String) value);
    } else if (value instanceof Integer) {
        editor.putInt(key, (Integer) value);
    } else if (value instanceof Long) {
        editor.putLong(key, (Long) value);
    } else if (value instanceof Float) {
        editor.putFloat(key, (Float) value);
    } else if (value instanceof Boolean) {
        editor.putBoolean(key, (Boolean) value);
    } else {
        throw new Exception("Unacceptable object type");
    }

    editor.commit();
}

/**
 * Return String
 * @param key
 * @return null default is null
 */
public String loadStringFromSharedPref(String key) throws Exception {
    SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
    String restoredText = prefs.getString(key, null);

    return restoredText;
}

/**
 * Return int
 * @param key
 * @return null default is -1
 */
public Integer loadIntegerFromSharedPref(String key) throws Exception {
    SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
    Integer restoredText = prefs.getInt(key, -1);

    return restoredText;
}

/**
 * Return float
 * @param key
 * @return null default is -1
 */
public Float loadFloatFromSharedPref(String key) throws Exception {
    SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
    Float restoredText = prefs.getFloat(key, -1);

    return restoredText;
}

/**
 * Return long
 * @param key
 * @return null default is -1
 */
public Long loadLongFromSharedPref(String key) throws Exception {
    SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
    Long restoredText = prefs.getLong(key, -1);

    return restoredText;
}

/**
 * Return boolean
 * @param key
 * @return null default is false
 */
public Boolean loadBooleanFromSharedPref(String key) throws Exception {
    SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
    Boolean restoredText = prefs.getBoolean(key, false);

    return restoredText;
}

}
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sp.edit();
editor.putString("Name","Jayesh");
editor.commit();
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String name = sp.getString("Name", "");
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sp.edit();
editor.putString("Name","Jayesh");
editor.commit();
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String name = sp.getString("Name", ""); // Second parameter is the default value.
要从共享首选项检索值,请执行以下操作:

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

// use a default value using new Date()
long l = prefs.getLong(dateTimeKey, new Date().getTime()); 
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Name","Harneet");
editor.apply();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = preferences.getString("Name", "");
if(!name.equalsIgnoreCase(""))
{
    name = name + "  Sethi";  /* Edit the value here*/
}
public String getPreferences(Context context, String prefKey) {
  SharedPreferences sharedPreferences = PreferenceManager
 .getDefaultSharedPreferences(context);
 return sharedPreferences.getString(prefKey, "");
}
import android.content.Context;
import android.content.SharedPreferences;

/**
 * Created by mete_ on 23.12.2016.
 */
public class HelperSharedPref {

Context mContext;

public HelperSharedPref(Context mContext) {
    this.mContext = mContext;
}

/**
 *
 * @param key Constant RC
 * @param value Only String, Integer, Long, Float, Boolean types
 */
public void saveToSharedPref(String key, Object value) throws Exception {
    SharedPreferences.Editor editor = mContext.getSharedPreferences(key, Context.MODE_PRIVATE).edit();
    if (value instanceof String) {
        editor.putString(key, (String) value);
    } else if (value instanceof Integer) {
        editor.putInt(key, (Integer) value);
    } else if (value instanceof Long) {
        editor.putLong(key, (Long) value);
    } else if (value instanceof Float) {
        editor.putFloat(key, (Float) value);
    } else if (value instanceof Boolean) {
        editor.putBoolean(key, (Boolean) value);
    } else {
        throw new Exception("Unacceptable object type");
    }

    editor.commit();
}

/**
 * Return String
 * @param key
 * @return null default is null
 */
public String loadStringFromSharedPref(String key) throws Exception {
    SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
    String restoredText = prefs.getString(key, null);

    return restoredText;
}

/**
 * Return int
 * @param key
 * @return null default is -1
 */
public Integer loadIntegerFromSharedPref(String key) throws Exception {
    SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
    Integer restoredText = prefs.getInt(key, -1);

    return restoredText;
}

/**
 * Return float
 * @param key
 * @return null default is -1
 */
public Float loadFloatFromSharedPref(String key) throws Exception {
    SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
    Float restoredText = prefs.getFloat(key, -1);

    return restoredText;
}

/**
 * Return long
 * @param key
 * @return null default is -1
 */
public Long loadLongFromSharedPref(String key) throws Exception {
    SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
    Long restoredText = prefs.getLong(key, -1);

    return restoredText;
}

/**
 * Return boolean
 * @param key
 * @return null default is false
 */
public Boolean loadBooleanFromSharedPref(String key) throws Exception {
    SharedPreferences prefs = mContext.getSharedPreferences(key, Context.MODE_PRIVATE);
    Boolean restoredText = prefs.getBoolean(key, false);

    return restoredText;
}

}
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sp.edit();
editor.putString("Name","Jayesh");
editor.commit();
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String name = sp.getString("Name", "");
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sp.edit();
editor.putString("Name","Jayesh");
editor.commit();
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String name = sp.getString("Name", ""); // Second parameter is the default value.

如何通过
SharedReferences
在中存储登录值的简单解决方案

您可以扩展
MainActivity
类或其他类,在这些类中存储“要保留的内容的值”。将其放入writer和reader类:

public static final String GAME_PREFERENCES_LOGIN = "Login";
这里
InputClass
分别是输入类和
OutputClass
是输出类

// This is a storage, put this in a class which you can extend or in both classes:
//(input and output)
public static final String GAME_PREFERENCES_LOGIN = "Login";

// String from the text input (can be from anywhere)
String login = inputLogin.getText().toString();

// then to add a value in InputCalss "SAVE",
SharedPreferences example = getSharedPreferences(GAME_PREFERENCES_LOGIN, 0);
Editor editor = example.edit();
editor.putString("value", login);
editor.commit();
现在您可以在其他地方使用它,就像其他类一样。以下是
OutputClass

SharedPreferences example = getSharedPreferences(GAME_PREFERENCES_LOGIN, 0);
String userString = example.getString("value", "defValue");

// the following will print it out in console
Logger.getLogger("Name of a OutputClass".class.getName()).log(Level.INFO, userString);
在这里,
mSaved
可以是任何
TextView
EditText
,我们可以从中提取字符串。您可以简单地指定一个字符串。此处文本将是保存从
mSaved
TextView
EditText
)获得的值的键


此外,不需要使用包名(即“com.example.app”)保存首选项文件。你可以提到你自己喜欢的名字。希望这有帮助

写:

SharedPreferences preferences = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Authentication_Id",userid.getText().toString());
editor.putString("Authentication_Password",password.getText().toString());
editor.putString("Authentication_Status","true");
editor.apply();
SharedPreferences prfs = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE);
String Astatus = prfs.getString("Authentication_Status", "");
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:orientation="vertical"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent" >

        <TextView
            android:id="@+id/text"  
            android:layout_width="fill_parent" 
            android:layout_height="wrap_content" 
            android:text="@string/hello" />
</LinearLayout>
String name = PreferenceManager.getDefaultSharedPreferences(this).getString("VarName","defaultValue");
阅读:

SharedPreferences preferences = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Authentication_Id",userid.getText().toString());
editor.putString("Authentication_Password",password.getText().toString());
editor.putString("Authentication_Status","true");
editor.apply();
SharedPreferences prfs = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE);
String Astatus = prfs.getString("Authentication_Status", "");
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:orientation="vertical"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent" >

        <TextView
            android:id="@+id/text"  
            android:layout_width="fill_parent" 
            android:layout_height="wrap_content" 
            android:text="@string/hello" />
</LinearLayout>
String name = PreferenceManager.getDefaultSharedPreferences(this).getString("VarName","defaultValue");

在任何应用程序中,都有可以通过
PreferenceManager
实例及其相关方法
getDefaultSharedPreferences(Context)
访问的默认首选项

使用
SharedReference
实例,可以使用getInt(字符串键,int-deffal)检索任何首选项的int值。我们对这种情况感兴趣的是相反的

在本例中,我们可以使用edit()修改本例中的
SharedReference
实例,并使用
putin(字符串键,int-newVal)
我们增加了应用程序的计数,该计数显示在应用程序之外并相应显示

为了进一步演示这一点,重新启动应用程序,然后再次启动应用程序,您会注意到每次重新启动应用程序时,计数都会增加

首选项demo.java

代码:

main.xml

代码:

SharedPreferences preferences = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Authentication_Id",userid.getText().toString());
editor.putString("Authentication_Password",password.getText().toString());
editor.putString("Authentication_Status","true");
editor.apply();
SharedPreferences prfs = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE);
String Astatus = prfs.getString("Authentication_Status", "");
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:orientation="vertical"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent" >

        <TextView
            android:id="@+id/text"  
            android:layout_width="fill_parent" 
            android:layout_height="wrap_content" 
            android:text="@string/hello" />
</LinearLayout>
String name = PreferenceManager.getDefaultSharedPreferences(this).getString("VarName","defaultValue");

存储信息

SharedPreferences preferences = getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("username", username.getText().toString());
editor.putString("password", password.getText().toString());
editor.putString("logged", "logged");
editor.commit();
重置您的首选项

Date dt = getSomeDate();
prefs.edit().putLong(dateTimeKey, dt.getTime()).apply();
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.commit();
prefs.edit().putLong("preference_file_key", 1010101).apply();
SharedPreferences sp = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
long lsp = sp.getLong("preference_file_key", -1);
使用此功能,您可以调用SharedReferences

TinyDB tinydb = new TinyDB(context);

tinydb.putInt("clickCount", 2);

tinydb.putString("userName", "john");
tinydb.putBoolean("isUserMale", true); 

tinydb.putList("MyUsers", mUsersArray);
tinydb.putImagePNG("DropBox/WorkImages", "MeAtlunch.png", lunchBitmap);

//These plus the corresponding get methods are all Included

如果您正在与团队中的其他开发人员一起开发一个大型应用程序,并且希望将所有内容组织得井井有条,而不需要分散的代码或不同的SharedReferences实例,您可以这样做:

//SharedPreferences manager class
public class SharedPrefs {

    //SharedPreferences file name
    private static String SHARED_PREFS_FILE_NAME = "my_app_shared_prefs";

    //here you can centralize all your shared prefs keys
    public static String KEY_MY_SHARED_BOOLEAN = "my_shared_boolean";
    public static String KEY_MY_SHARED_FOO = "my_shared_foo";

    //get the SharedPreferences object instance
    //create SharedPreferences file if not present


    private static SharedPreferences getPrefs(Context context) {
        return context.getSharedPreferences(SHARED_PREFS_FILE_NAME, Context.MODE_PRIVATE);
    }

    //Save Booleans
    public static void savePref(Context context, String key, boolean value) {
        getPrefs(context).edit().putBoolean(key, value).commit();       
    }

    //Get Booleans
    public static boolean getBoolean(Context context, String key) {
        return getPrefs(context).getBoolean(key, false);
    }

    //Get Booleans if not found return a predefined default value
    public static boolean getBoolean(Context context, String key, boolean defaultValue) {
        return getPrefs(context).getBoolean(key, defaultValue);
    }

    //Strings
    public static void save(Context context, String key, String value) {
        getPrefs(context).edit().putString(key, value).commit();
    }

    public static String getString(Context context, String key) {
        return getPrefs(context).getString(key, "");
    }

    public static String getString(Context context, String key, String defaultValue) {
        return getPrefs(context).getString(key, defaultValue);
    }

    //Integers
    public static void save(Context context, String key, int value) {
        getPrefs(context).edit().putInt(key, value).commit();
    }

    public static int getInt(Context context, String key) {
        return getPrefs(context).getInt(key, 0);
    }

    public static int getInt(Context context, String key, int defaultValue) {
        return getPrefs(context).getInt(key, defaultValue);
    }

    //Floats
    public static void save(Context context, String key, float value) {
        getPrefs(context).edit().putFloat(key, value).commit();
    }

    public static float getFloat(Context context, String key) {
        return getPrefs(context).getFloat(key, 0);
    }

    public static float getFloat(Context context, String key, float defaultValue) {
        return getPrefs(context).getFloat(key, defaultValue);
    }

    //Longs
    public static void save(Context context, String key, long value) {
        getPrefs(context).edit().putLong(key, value).commit();
    }

    public static long getLong(Context context, String key) {
        return getPrefs(context).getLong(key, 0);
    }

    public static long getLong(Context context, String key, long defaultValue) {
        return getPrefs(context).getLong(key, defaultValue);
    }

    //StringSets
    public static void save(Context context, String key, Set<String> value) {
        getPrefs(context).edit().putStringSet(key, value).commit();
    }

    public static Set<String> getStringSet(Context context, String key) {
        return getPrefs(context).getStringSet(key, null);
    }

    public static Set<String> getStringSet(Context context, String key, Set<String> defaultValue) {
        return getPrefs(context).getStringSet(key, defaultValue);
    }
}
您可以通过这种方式检索您的SharedReference

//saving a boolean into prefs
SharedPrefs.savePref(this, SharedPrefs.KEY_MY_SHARED_BOOLEAN, booleanVar);
//getting a boolean from prefs
booleanVar = SharedPrefs.getBoolean(this, SharedPrefs.KEY_MY_SHARED_BOOLEAN);
其基本思想是将内容存储在XML文件中

  • 声明您的xml文件路径。(如果您没有此文件,Android将创建它。如果您有此文件,Android将访问它。)

  • 将值写入共享首选项

    Date dt = getSomeDate();
    prefs.edit().putLong(dateTimeKey, dt.getTime()).apply();
    
    SharedPreferences.Editor editor = preferences.edit();
    editor.clear();
    editor.commit();
    
    prefs.edit().putLong("preference_file_key", 1010101).apply();
    
    SharedPreferences sp = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
    long lsp = sp.getLong("preference_file_key", -1);
    
    preference\u file\u键
    是共享首选项文件的名称。而
    1010101
    是您需要存储的值

    apply()
    最后是保存更改。如果从
    apply()
    中得到错误,请将其更改为
    commit()
    。所以这个替代的句子是

    prefs.edit().putLong("preference_file_key", 1010101).commit();
    
  • 读取共享首选项

    Date dt = getSomeDate();
    prefs.edit().putLong(dateTimeKey, dt.getTime()).apply();
    
    SharedPreferences.Editor editor = preferences.edit();
    editor.clear();
    editor.commit();
    
    prefs.edit().putLong("preference_file_key", 1010101).apply();
    
    SharedPreferences sp = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
    long lsp = sp.getLong("preference_file_key", -1);
    
    lsp
    如果
    preference\u file\u key
    没有值,则将为
    -1
    。如果“preference\u file\u key”有一个值,它将返回该值

  • 整个编写代码是

        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.
    
    阅读的代码是

        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
    

    我想在这里补充一点,当使用SharedReferences时,这个问题的大多数代码片段都会有类似MODE_PRIVATE的内容。嗯,MODE_PRIVATE意味着,无论您在这个共享首选项中写入什么,都只能由您的应用程序读取

    无论传递给getSharedReferences()方法的键是什么,android都会创建一个具有该名称的文件,并将首选项数据存储到其中。 还请记住,getSharedReferences()应该在您希望应用程序具有多个首选项文件时使用。如果要使用单个首选项文件并将所有键值对存储到其中,请使用getSharedReference()方法。奇怪的是,为什么每个人(包括我自己)都只是简单地使用getSharedReferences()风格,而根本不理解这两者之间的区别

    下面的视频教程应该会有所帮助
    保存

    PreferenceManager.getDefaultSharedPreferences(this).edit().putString("VarName","your value").apply();
    
    检索:

    SharedPreferences preferences = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString("Authentication_Id",userid.getText().toString());
    editor.putString("Authentication_Password",password.getText().toString());
    editor.putString("Authentication_Status","true");
    editor.apply();
    
    SharedPreferences prfs = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE);
    String Astatus = prfs.getString("Authentication_Status", "");
    
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="vertical"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent" >
    
            <TextView
                android:id="@+id/text"  
                android:layout_width="fill_parent" 
                android:layout_height="wrap_content" 
                android:text="@string/hello" />
    </LinearLayout>
    
    String name = PreferenceManager.getDefaultSharedPreferences(this).getString("VarName","defaultValue");
    
    默认值为:如果此首选项不存在,则返回的值

    您可以在中使用getActivity()getApplicationContext()更改“” 一些案例


    人们推荐使用共享参考资料的方法有很多。我做了一个决定。示例中的关键点是使用ApplicationContext和单个SharedReferences对象。这演示了如何使用具有以下功能的SharedReferences:-

    • 使用singelton类访问/更新SharedReferences
    • 无需为读/写SharedReference始终传递上下文
    • 它使用apply()而不是commit()
    • apply()是异步保存,不返回任何内容,它首先更新内存中的值并写入更改