首页 > 解决方案 > SharedPreferences 在重复的 Android Studio 项目中不起作用

问题描述

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

      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 变量只返回默认值(“”)。

标签: javaandroidandroid-studiosharedpreferences

解决方案


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,"");

推荐阅读