【问题标题】:NullPointer when getting response from REST using Retrofit使用 Retrofit 从 REST 获取响应时出现 NullPointer
【发布时间】:2018-08-18 15:51:56
【问题描述】:

我正在使用 Retrofit 与 Android 上的 REST API 通信,但我收到如下错误 NullPointerException。我尝试使用邮递员,API 工作正常,我得到了响应。

java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“java.util.List ukmutilizer.project.com.ukm_utilizer.model.CheckEmail.getData()”

这是我的活动课

private void sendRequest(String checkEmail){
    ApiInterface apiService =  ApiClient.getClient().create(ApiInterface.class);

    Call<CheckEmail> call = apiService.getEmailStatus(checkEmail);

    call.enqueue(new Callback<CheckEmail>() {
        @Override
        public void onResponse(Call<CheckEmail> call, Response<CheckEmail> response) {

            CheckEmailData emailDataList = response.body().getData();
            Log.d("Numer of Data : ", String.valueOf(response.body().getData()));

        }

        @Override
        public void onFailure(Call<CheckEmail> call, Throwable t) {
            Toast.makeText(CheckEmailPage.this, "Something went wrong!", Toast.LENGTH_SHORT).show();
            Log.e("Error Retrofit : ", String.valueOf(t));

        }
    });

这是 ApiInterface

public interface ApiInterface {
@POST("users/check_status")
Call<CheckEmail> getEmailStatus(@Body String email);
}

这是改造实例

`public class ApiClient {

public static final String BASE_URL = "https://f49d9d29-8471-4126-95b0-1ec3d18eda94.mock.pstmn.io/v1/";
private static Retrofit retrofit = null;

public static Retrofit getClient(){

    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient httpClient = new OkHttpClient.Builder().addInterceptor(logging).build();


    if(retrofit == null){
        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    return retrofit;
   }
}`

这是 json 响应

{
"code": 1000,
"message": "OK",
"data": {
    "id": "1",
    "email": "test@gmail.com",
    "status": "1",
    "name": "test",
    "category": "2"
  }
}

这是 POJO

`public class CheckEmail {


    @SerializedName("code")
    @Expose
    private Integer code;
    @SerializedName("message")
    @Expose
    private String message;
    @SerializedName("data")
    @Expose
    private CheckEmailData data;

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public CheckEmailData getData() {
        return data;
    }

    public void setData(CheckEmailData data) {
        this.data = data;
    }
}`

CheckEmailData POJO

`public class CheckEmailData {
@SerializedName("id")
@Expose
private String id;

@SerializedName("email")
@Expose
private String email;

@SerializedName("status")
@Expose
private String status;

@SerializedName("name")
@Expose
private String name;

@SerializedName("category")
@Expose
private String category;

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getStatus() {
    return status;
}

public void setStatus(String status) {
    this.status = status;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getCategory() {
    return category;
}

public void setCategory(String category) {
    this.category = category;
}

}`

【问题讨论】:

标签: java android gson retrofit2


【解决方案1】:

你只有一个数据,json对象,来自json响应的api

{
"code": 1000,
"message": "OK",
"data": {
    "id": "1",
    "email": "test@gmail.com",
    "status": "1",
    "name": "test",
    "category": "2"
  }
}

但您将数据声明为 List 对象,它期望上面的 data 采用 json 数组格式。

您应该将列表更改为

@SerializedName("data")
@Expose
private CheckEmailData data;

我相信会没事的。

【讨论】:

  • 你好,我一直按照你的方法,但仍然出现错误。
  • 您可以在问题中发布您的更改吗?
【解决方案2】:

在那个 JSON 中,“数据”是一个对象,而不是一个数组。在您的 CheckEmail 类中,将 private List&lt;CheckEmailData&gt; data; 更改为 private CheckEmailData data;

【讨论】:

  • 我在 17 秒内更快:p
  • 您好,我一直在更改我的代码并按照您的方式进行操作,但错误仍然出现public void onResponse(Call&lt;CheckEmail&gt; call, Response&lt;CheckEmail&gt; response) { CheckEmailData emailDataList = response.body().getData(); Log.d("Numer of Data : ", String.valueOf(response.body().getData())); }
【解决方案3】:

在访问响应中的数据之前,您应该检查响应本身是否正常。

@Override
public void onResponse(Call<CheckEmail> call, Response<CheckEmail> response) {
    if(response.isSuccessfull()){
        //if you are sure that when the response is OK the list is not null
        //you can leave this line below to hide the lint warning, otherwise
        //before accessing the list with getData() check that response.body() is not null
        //noinspection ConstantConditions
        List<CheckEmailData> emailDataList = response.body().getData();
        Log.d("Numer of Data : ", String.valueOf(emailDataList.size()));
        for (CheckEmailData emailData : emailDataList){
            Log.d("Successfull : ", String.valueOf(emailData.getStatus()));
        }
    } else {
        //you got an error response, handle it
    }
}

【讨论】:

    【解决方案4】:

    我的问题已经解决了

    我在下面的界面上添加了标题

    public interface ApiInterface {
    @Headers({
            "Content-Type:application/x-www-form-urlencoded"
    })
    
    @POST("v1/users/check_status")
    Call<CheckEmail> getEmailStatus(@Body String email);
    }
    

    【讨论】:

      猜你喜欢
      • 2016-02-22
      • 2016-11-18
      • 1970-01-01
      • 1970-01-01
      • 2016-11-03
      • 2016-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多