Android Java:SharedPreferences已设置但无法读取的问题
我的应用启动时会为“默认字体大小”创建默认SharedPreferences,具体是AppUtils类中的public static final String DEFAULT_FONT_SIZE_KEY = "defaultFontSize";。我已将该SharedPreferences的默认值设为16,但创建后立即dump所有键值对却无任何返回——此时尚未调整字体大小键的值,仅完成创建并检查存储情况,dump无结果。
应用的android.intent.action.MAIN对应WelcomeActivity类,在该类的onCreate中声明SharedPreferences并调用AppUtils.initializeSharedPreferences初始化:
... private SharedPreferences sharedPreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_welcome); AppUtils.initializeSharedPreferences(this); sharedPreferences = AppUtils.getSharedPreferences(); ...
initializeSharedPreferences方法仅调用一次,用于创建DEFAULT_FONT_SIZE_KEY(不存在时创建SharedPreferences),该方法位于AppUtils类:
public static void initializeSharedPreferences(Context context) { if (sharedPreferences == null) { sharedPreferences = context.getSharedPreferences("SongTrackerApp", Context.MODE_PRIVATE); if (getDefaultFontSize(sharedPreferences) == 0) { saveDefaultFontSize(sharedPreferences, 16); } Log.d("AdjustTextSize", "(AppUtils) INIT: line #17, 1st Value-DEFAULT_FONT_SIZE_KEY: " + getDefaultFontSize(sharedPreferences)); } Log.d("AdjustTextSize", "(AppUtils) INIT: line #19, DEFAULT_FONT_SIZE_KEY: " + getDefaultFontSize(sharedPreferences) + ", context: " + context); }
同时在WelcomeActivity的onCreate中获取DEFAULT_FONT_SIZE_KEY的值,并调用dbHelper.logSharedPreferencesEntriesdump所有SharedPreferences:
// Get all key-value pairs from SharedPreferences if (sharedPreferences != null) { // Print out all sharedPreferences: Log.d("AdjustTextSize", "(WelcomeActivity) line #77, DEFAULT_FONT_SIZE_KEY: " + AppUtils.getDefaultFontSize(sharedPreferences)); dbHelper.logSharedPreferencesEntries(sharedPreferences, "WelcomeActivity"); }
Log.d显示DEFAULT_FONT_SIZE_KEY的SharedPreferences存在:
(WelcomeActivity) line #77, DEFAULT_FONT_SIZE_KEY: 16.0
但调用DatabaseHelper的logSharedPreferencesEntriesdump时无返回,方法中if (allEntries.isEmpty())判断为true:
public void logSharedPreferencesEntries(SharedPreferences sharedPreferences, String pageName) { Map<String, ?> allEntries = sharedPreferences.getAll(); // Check if there are any entries if (allEntries.isEmpty()) { Log.d("AdjustTextSize", "(DBHelper via: " + pageName + ") DUMP line #1063 No sharedPreference keys found"); return; } // Iterate through the entries and log them for (Map.Entry<String, ?> entry : allEntries.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); // Display constant name, key name, and value in Log.d String constantName = findConstantName(key); Log.d("AdjustTextSize", "(DBHelper via: " + pageName + ") DUMP line #1072 - Constant: " + constantName + ", Key: " + key + ", Value: " + value.toString()); } }
我已查阅相关旧条目,未找到2023年该问题的解决方案。
编辑:2023.12.14
已将editor.apply();替换为同步的editor.commit();,但调用初始化方法后立即dump仍提示无键值对。多次修改字体大小后dump会显示Constant: DEFAULT_FONT_SIZE_KEY, Key: defaultFontSize, Value: 0.0,但值不准确,此为另一问题,现寻求该读取异常的排查建议!
内容的提问来源于stack exchange,提问作者kiteandwindsurfer

