java - 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 变量只返回默认值(“”)。
解决方案
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,"");
推荐阅读
- python - 定义一个函数来计算文件中的行数,包含某个子字符串
- android - 当应用程序中连接了firebase但它没有显示正确的结果时我们应该怎么做?
- python - 计算特定时间跨度的数据框列中的最大出现次数
- visual-studio-code - 如何使用 editor.tokenColorCustomizations 而不是工作台更改 vscode 中的编辑器背景颜色
- java - Webclient 发送没有正文的 POST 将得到 IllegalStateException
- cross-compiling - 重建 Android 内核时出现“CROSS_COMPILE_ARM32 未定义或为空”
- jquery - 如何从具有 div 的数组中排除具有孩子的特定父母?
- java - 无递归的二叉树分支求和
- java - 如何在 java 中运行 MongodDB dbStats 命令?
- php - 向数据库插入未知数量的输入