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

Android应用Retrofit2对接Laravel注册时遇NullPointerException求助

Retrofit2对接Laravel注册空指针问题解决
  • 空指针根源:当响应码不是201时,response.body()大概率为null,直接调用dr.getFail()触发NullPointerException。原因通常是Laravel后端返回错误响应时,未输出符合DefaultResponse结构的JSON,或者响应Content-Type非application/json,导致Retrofit无法解析出对象。

  • 修复步骤:

    1. 强制判空+错误响应解析:在使用响应体前必须做非空校验,同时通过errorBody()获取错误响应内容:
      @Override
      public void onResponse(Call<DefaultResponse> call, Response<DefaultResponse> response) {
          if (response.isSuccessful()) {
              DefaultResponse dr = response.body();
              if (dr != null) {
                  Toast.makeText(RegisterActivity.this, dr.getSuccess(), Toast.LENGTH_LONG).show();
              }
          } else {
              // 解析错误响应体
              try {
                  String errorContent = response.errorBody().string();
                  DefaultResponse errorResp = new Gson().fromJson(errorContent, DefaultResponse.class);
                  if (errorResp != null && errorResp.getFail() != null) {
                      Toast.makeText(RegisterActivity.this, errorResp.getFail(), Toast.LENGTH_SHORT).show();
                  } else {
                      Toast.makeText(RegisterActivity.this, "注册失败:未知错误", Toast.LENGTH_SHORT).show();
                  }
              } catch (IOException e) {
                  e.printStackTrace();
                  Toast.makeText(RegisterActivity.this, "注册失败:响应解析出错", Toast.LENGTH_SHORT).show();
              }
          }
      }
      
    2. 修正Laravel后端响应格式:确保错误场景下返回结构匹配DefaultResponse的JSON,同时指定Content-Type:
      // 注册失败示例(如验证不通过)
      return response()->json([
          'fail' => '邮箱已存在或密码格式不符合要求'
      ], 422);
      
    3. 完善网络失败处理:不要空实现onFailure,处理网络异常:
      @Override
      public void onFailure(Call<DefaultResponse> call, Throwable t) {
          Toast.makeText(RegisterActivity.this, "网络请求失败:" + t.getMessage(), Toast.LENGTH_SHORT).show();
      }
      
  • 额外优化:给DefaultResponse的字段添加@Nullable注解(AndroidX环境),或者在get方法中做非空兜底,避免后续调用触发空指针。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 19:27:05