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

Android开发:无法获取SharedPreferences值,遇NullPointerException报错

问题分析

从报错日志能明确看到,空指针异常出现在getApplicationContext()的调用上,核心原因是:你的User类错误地继承了AppCompatActivity,但你是通过new User(name)手动创建实例的——Activity作为Android四大组件之一,只有系统才能完成它的Context初始化,手动new出来的Activity子类实例完全没有经过系统初始化流程,所以Context是无效的null值,调用getApplicationContext()自然就会报错。

解决方案

你需要把User重构为普通的Java模型类,去掉Activity继承,同时在需要访问SharedPreferences的方法中传入有效的Context。

修改后的User.java代码

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

// 去掉AppCompatActivity继承,改为普通Java类
public class User {
    private String name;
    private int guthaben;
    private int getrunken;

    public void setName(String name){
        this.name = name;
    }
    public String getName(){
        return name;
    }
    public void setGuthaben(int guthaben){
        this.guthaben = guthaben;
    }
    public int getGuthaben(){
        return guthaben;
    }
    public void setGetrunken(int getrunken){
        this.getrunken = getrunken;
    }
    public int getGetrunken(){
        return getrunken;
    }

    // 构造方法新增Context参数,用于获取SharedPreferences
    public User(Context context, String name){
        this.name = name;
        this.guthaben = getGuthabenFromPreference(context, name);
        this.getrunken = getGetrunkenFromPreference(context, name);
    }

    // 方法新增Context参数,通过传入的Context获取SharedPreferences
    public int getGuthabenFromPreference(Context context, String name){
        SharedPreferences Guthaben_User = context.getSharedPreferences(name, 0);
        return Guthaben_User.getInt("Guthaben", 0);
    }

    public int getGetrunkenFromPreference(Context context, String name){
        SharedPreferences Getrunken_User = context.getSharedPreferences(name, 0);
        return Getrunken_User.getInt("Getrunken", 0);
    }
}

修改ActivityUser中的调用逻辑

在ActivityUser.onCreate()里创建User实例时,传入当前Activity的Context(直接用this即可):

// 替换原来的new User("用户名")写法
User user = new User(this, "你的用户名");
额外提醒
  • 永远不要手动创建Activity、Service这类Android组件的实例,它们的生命周期必须由系统管理。
  • 如果普通类需要访问Android系统资源(比如SharedPreferences、数据库),一定要通过传入有效的Context实现;如果需要长期持有Context,建议使用getApplicationContext()来避免Activity内存泄漏,但要注意使用场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:34:30