SharedPreferences 在重复的 Android Studio 项目中不起作用

SharedPreferences not working in a duplicated Android Studio project

我创建了一个示例应用程序,其中我使用了如下共享首选项:

      SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
                    
      SharedPreferences.Editor editor = sharedPref.edit();

      editor.putString("data", "This is my data...");

                    editor.apply();

并像这样读取数据:

    SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
    String base_data = sharedPref.getString("data", "");

此代码在示例应用程序中有效,但是当我将示例应用程序项目文件复制并粘贴到 android studio 中的另一个项目时,SharedPreferences 似乎不起作用。我已经尝试了一切,但它不起作用。请救我不要发疯...

在“重复”项目中 base_data 变量只是 returns 默认值 ("")。

您需要提供一个名称来识别首选项文件

private static final Object MY_PREFS_NAME = "MY_PREFS";

 SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
    editor.putString("data","This is my data...");
    editor.apply();

从首选项中获取数据:

SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); 
String data = prefs.getString("data", "No data");

或者试试这个 class

public class PrefManager {

SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;

// shared pref mode
int PRIVATE_MODE = 0;

// Shared preferences file name
private static final String PREF_NAME = "your_app_name";

private static final String IS_FIRST_TIME_LAUNCH = "IsFirstTimeLaunch";

public PrefManager(Context context) {
    this._context = context;
    pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
    editor = pref.edit();
}

public void setBoolean(String PREF_NAME,Boolean val) {
    editor.putBoolean(PREF_NAME, val);
    editor.commit();
}
public void setString(String PREF_NAME,String VAL) {
    editor.putString(PREF_NAME, VAL);
    editor.commit();
}
public void setInt(String PREF_NAME,int VAL) {
    editor.putInt(PREF_NAME, VAL);
    editor.commit();
}
public boolean getBoolean(String PREF_NAME) {
    return pref.getBoolean(PREF_NAME,true);
}
public void remove(String PREF_NAME){
    if(pref.contains(PREF_NAME)){
        editor.remove(PREF_NAME);
        editor.commit();
    }
}
public String getString(String PREF_NAME) {
    if(pref.contains(PREF_NAME)){
        return pref.getString(PREF_NAME,null);
    }
    return  "";
}

public int getInt(String key) {
    return pref.getInt(key,0);
}

}

然后

 PrefManager prefManager = new PrefManager(context);
 prefManager.setString("data","mydata");
 String data = prefManager.getString("data");
public static final String PREFS_GAME ="PLAY";
public static final String GAME_SCORE= "GameScore";    

//========保存数据的代码===================

SharedPreferences sp = getApplicationContext.getSharedPreferences(PREFS_GAME ,Context.MODE_PRIVATE);
sp.edit().putString(GAME_SCORE,"100").commit();

//========= 保存/检索数据的代码==============

SharedPreferences sp = getApplicationContext.getSharedPreferences(PREFS_GAME ,Context.MODE_PRIVATE);
String sc  = sp.getString(GAME_SCORE,"");