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

Android调用getSharedPreferences触发空指针异常问题求助

问题原因分析

空指针异常的根源是传递给TokenInterceptor.getClients()的Context为null,导致调用context.getSharedPreferences()时触发空对象引用错误。具体问题点:

  1. 在ApiClient.getClient()中,调用new TokenInterceptor().getClients()时未传入Context参数,但getClients方法依赖该参数获取SharedPreferences
  2. TokenInterceptor中直接使用MODE_PRIVATE,需明确指定为Context.MODE_PRIVATE以避免作用域问题
解决方案

1. 修改ApiClient.getClient()方法,添加Context参数并传递给getClients

public static Retrofit getClient(Context context) {
    OkHttpClient client = new TokenInterceptor().getClients(context);
    if (retrofit == null) {
        Gson gson = new GsonBuilder().setLenient()
                                     .create();
        retrofit = new Retrofit.Builder()
                    .client(client)
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .build();
    }
    return retrofit;
}

2. 修正TokenInterceptor中MODE_PRIVATE的引用

// 原代码
// SharedPreferences preferences = context.getSharedPreferences("logged", MODE_PRIVATE);
// 修改为
SharedPreferences preferences = context.getSharedPreferences("logged", Context.MODE_PRIVATE);

3. 在MainActivity中调用ApiClient.getClient()时传入有效Context

// 在CallLoginService方法中调用时
Retrofit retrofit = ApiClient.getClient(MainActivity.this);

额外优化建议

你的MainActivity中直接将完整的ResponseJson存储为token,这可能不符合接口要求。建议从解析后的tokenResponse对象中提取实际token值:

token = objResp.getToken(); // 替换为tokenResponse类中对应的getter方法
editor.putString("token", token);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 15:45:54