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

Android中Retrofit请求数据出现NullPointerException问题求助

解决Retrofit获取数据时的NullPointerException问题

首先,你的错误根源是response.body()返回了null,导致后续调用responseCustomerData.getData()时触发空指针异常。我们一步步来排查和解决:

1. 先确认HTTP请求是否成功

Retrofit只有当响应状态码是2xx(比如200)时,response.body()才会返回非null值。如果是4xx/5xx错误,body()会直接为null,这时候必须先查看错误响应的内容才能定位问题。

修改你的onResponse方法,先做请求成功判断:

@Override
public void onResponse(Call<ResponseCustomerData> call, Response<ResponseCustomerData> response) {
    if (response.isSuccessful()) {
        // 处理成功响应
        ResponseCustomerData responseCustomerData = response.body();
        // 双重空判断,避免后续调用出错
        if (responseCustomerData != null && responseCustomerData.getData() != null) {
            getCustomerList.clear();
            getCustomerList.addAll(responseCustomerData.getData());
            adapterCustomer.notifyDataSetChanged();
            
            // 注意:你之前直接用new出来的getCustomer是空对象,要从列表里取真实数据
            if (!getCustomerList.isEmpty()) {
                getCustomer = getCustomerList.get(0); // 示例取第一个数据
                String tanggalLahir = getCustomer.getTanggalLahir().substring(0,10);
                Toast.makeText(UserMenuActivity.this, tanggalLahir, Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(UserMenuActivity.this, "接口返回数据为空", Toast.LENGTH_SHORT).show();
        }
    } else {
        // 打印错误响应内容,方便排查后端问题
        try {
            String errorContent = response.errorBody().string();
            Log.d("API Error", "错误码:" + response.code() + ",错误内容:" + errorContent);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Toast.makeText(UserMenuActivity.this, "请求失败:" + response.code(), Toast.LENGTH_SHORT).show();
    }
}

2. 检查ResponseCustomerData模型与API返回的JSON结构是否匹配

Gson解析失败会直接返回null,所以要确保你的模型类和API返回的JSON完全对齐:

  • 确认JSON的最外层是否包含data字段,且data是一个数组(对应你的List<getCustomer>);
  • 检查getCustomer类的字段名是否和JSON的key完全一致,如果不一致,要添加@SerializedName注解(比如JSON里是tanggal_lahir,你的字段是tanggalLahir,就需要加@SerializedName("tanggal_lahir"));
  • 确保ResponseCustomerData类正确定义了List<getCustomer> getData()的getter方法,且字段修饰符是public或者有正确的getter。

3. 验证请求头的Token是否正确

你用了"bearer " + responseLoginHome.getData().getAuth_token(),要确认:

  • responseLoginHome.getData().getAuth_token()是否不为null,且是后端认可的有效Token;
  • "bearer "后面的空格是否正确(标准格式是Bearer <token>,有些后端严格区分大小写,建议改成"Bearer ");
  • 后端是否要求Token放在Authorization请求头里(你的AdminFullService接口定义里要确保@Headers或者@Header注解正确)。

4. 修正代码里的其他潜在问题

  • 你之前直接调用getCustomer.getTanggalLahir(),但getCustomer是new getCustomer()出来的空对象,根本没有数据,必须从加载后的getCustomerList里取真实数据;
  • 上下文要正确:UserMenu.this应该改成UserMenuActivity.this,因为你的Activity类是UserMenuActivity;
  • 确保getCustomerList已经初始化(比如private List<getCustomer> getCustomerList = new ArrayList<>();),否则调用clear()和addAll()也会触发空指针。

额外排查技巧:开启Retrofit日志拦截器

添加日志拦截器可以在Logcat里看到完整的请求和响应内容,快速定位问题:

  1. 先添加依赖:
implementation 'com.squareup.okhttp3:logging-interceptor:4.11.0'
  1. 配置Retrofit时添加拦截器:
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY); // 打印完整的请求响应
OkHttpClient client = new OkHttpClient.Builder()
    .addInterceptor(logging)
    .build();

retrofit = new Retrofit.Builder()
    .baseUrl("http://172.31.32.17:9290/")
    .client(client)
    .addConverterFactory(GsonConverterFactory.create())
    .build();

这样就能看到请求头、请求体、响应头和响应体的完整内容,方便判断是请求格式问题还是后端返回格式问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:25:33