You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android应用创建独立SharedPreferences文件失败问题排查

问题分析与解决方案

你的实现目前是不正确的,导致两个Activity的SharedPreferences数据互相干扰的核心原因很明确:

在两个类的构造函数中,你都使用了mContext.getPackageName()作为SharedPreferences的文件名:

mPreferencesIrigasi = mContext.getSharedPreferences(mContext.getPackageName(), Context.MODE_PRIVATE);
mPreferences = mContext.getSharedPreferences(mContext.getPackageName(), Context.MODE_PRIVATE);

同一个Android应用的包名是全局唯一的,所以这两个类实际上在操作同一个SharedPreferences文件——不管你在哪个Activity里写入数据,最终都会存在同一个文件中,自然会出现Activity1写入的值能在Activity2中被读取到的情况。


修正方案

你已经提前定义了各自独立的sharedPrefFile变量,只需要把注释掉的代码恢复,用这个自定义的唯一文件名来创建SharedPreferences实例即可:

修正后的SimpanWaktuIrigasi构造函数

private SimpanWaktuIrigasi(Context context) {
    mContext = context;
    // 使用自定义的唯一文件名,替代包名
    mPreferencesIrigasi = mContext.getSharedPreferences(sharedPrefFile, Context.MODE_PRIVATE);
}

修正后的SimpanWaktuTimer构造函数

private SimpanWaktuTimer(Context context) {
    mContext = context;
    // 使用自定义的唯一文件名,替代包名
    mPreferences = mContext.getSharedPreferences(sharedPrefFile, Context.MODE_PRIVATE);
}

这样两个类就会分别创建并操作com.example.e_pertanian.irigasi和com.example.e_pertanian.watering这两个完全独立的SharedPreferences文件,数据就不会互相干扰了。


额外优化建议

  • 为了避免Context泄漏,在获取单例的时候建议传入Application Context(比如context.getApplicationContext()),而不是Activity的Context,这样即使Activity被销毁,也不会影响单例的正常运行。
  • 可以把分散的写入操作合并,比如一次性写入时、分、秒,减少IO操作次数:
public void writeWaktu(int jam, int menit, int detik) {
    SharedPreferences.Editor preferencesEditor = mPreferencesIrigasi.edit();
    preferencesEditor.putInt(COUNT_JAM, jam);
    preferencesEditor.putInt(COUNT_MENIT, menit);
    preferencesEditor.putInt(COUNT_DETIK, detik);
    preferencesEditor.apply();
}

内容的提问来源于stack exchange,提问作者Yustina Yasin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:50:57