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

如何在非Activity类中使用SharedPreferences实现数据存取?现有代码报错求助

解决非Activity类中使用SharedPreferences的问题

这个问题很常见,核心原因是:getSharedPreferences()是Context类的成员方法,你的test类既没有继承Context相关组件(比如Activity、Service),也没有持有Context实例,直接用this调用肯定会报错。

下面给你两种简单可靠的解决方案:

方案一:通过构造方法传入Context(推荐)

给你的类添加一个需要传入Context的构造方法,同时建议使用ApplicationContext来避免内存泄漏:

package com.example.keypass;
import android.content.Context;
import android.content.SharedPreferences;

// 类名建议遵循Java规范,首字母大写
public class Test {
    private SharedPreferences sharedPreferences;

    // 构造方法中传入Context
    public Test(Context context) {
        // 使用ApplicationContext,避免持有Activity引用导致内存泄漏
        Context appContext = context.getApplicationContext();
        sharedPreferences = appContext.getSharedPreferences("com.example.keypass", Context.MODE_PRIVATE);
    }

    public void loadInt(){
        int usrPassword = sharedPreferences.getInt("meinInteger", 0);
        // 这里可以添加对获取到的数值的后续逻辑
    }
}

调用方式(在Activity中):

Test test = new Test(this);
test.loadInt();

方案二:通过静态方法传入Context

如果你的类不需要实例化,也可以直接写一个静态方法,每次调用时传入Context:

package com.example.keypass;
import android.content.Context;
import android.content.SharedPreferences;

public class Test {

    public static int loadInt(Context context){
        Context appContext = context.getApplicationContext();
        SharedPreferences sharedPreferences = appContext.getSharedPreferences("com.example.keypass", Context.MODE_PRIVATE);
        return sharedPreferences.getInt("meinInteger", 0);
    }
}

调用方式(在Activity中):

int userPassword = Test.loadInt(this);

重要注意事项

  • 永远优先使用ApplicationContext而非Activity的Context:如果你的类会长期存在(比如单例),持有Activity的引用会导致Activity无法被GC回收,引发内存泄漏。
  • 遵循Java命名规范:类名首字母大写(把test改成Test),成员变量建议用private修饰,提高代码封装性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 06:47:45