简体   繁体   English

Retrofit 响应返回 null 在 onResponse function (单个 Z0ECD11C1D7A23BB87402FZA18 对象)

[英]Retrofit response return null in onResponse function (single JSON object)

I'm try to get response from retrofit API after register the user.注册用户后,我尝试从 retrofit API 获得响应。

I get null from response.body() function我从response.body() function 得到 null

Register URL: https://apitest10101.000webhostapp.com/alaa-apii/public/createuser (Method POST)注册URL: https://apitest10101.000webhostapp.com/alaa-apii/public/createuser (方法POST)

The API return single object JSON like API 返回单 object JSON 之类

{
    "error": true,
    "message": "User Already Exists"
}

在此处输入图像描述 "response work after tested in postman" “在邮递员中测试后的响应工作”

RegisterActivity.java RegisterActivity.java

public void register(View view) {

       if(Validate())
       {
           Log.d("####", "OKAAAAAY");

            first_name = first_name_edit.getText().toString().trim();
            last_name = last_name_edit.getText().toString().trim();
            email = email_edit.getText().toString().trim();
            password = password_edit.getText().toString().trim();
            phone = Integer.parseInt(phone_edit.getText().toString().trim());
            state = state_edit.getText().toString().trim();
            block = block_edit.getText().toString().trim();
            street = street_edit.getText().toString().trim();
            building = buidling_edit.getText().toString().trim();
            floor = floor_edit.getText().toString().trim();
            flat = flat_edit.getText().toString().trim();


          Call<ResultModel> call = RetrofitClient
                .getInstance()
                .getApi()
                .createUser(first_name, last_name, email, password, phone, postionOfReigon, state, block, street, building, floor, flat);

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

                  boolean error = false;
                  String mass = null;
                  if (response.body() != null) { // response null  !!!!!!!!!!!
                      error = response.body().getError();
                      mass = response.body().getMessage();
                      Log.d("#####", error + "------" + mass);
                  }


                      Log.d("#####", error + "------" + mass);

              }

              @Override
              public void onFailure(Call<ResultModel> call, Throwable t) {
                  Toast.makeText(RegisterActivity.this, t.getMessage(), Toast.LENGTH_LONG).show();

              }
          });


       }
       else
       {
           Log.d("####", "NNNOOTT OKAAAAAY");
       }

    }

If I remove if statement in response.body() I got this error in log如果我删除response.body()中的 if 语句,我会在日志中收到此错误

2019-11-10 12:45:51.242 21211-21211/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myapplication, PID: 21211
    java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Boolean com.example.myapplication.ResultModel.getError()' on a null object reference
        at com.example.myapplication.RegisterActivity$2.onResponse(RegisterActivity.java:161)
        at retrofit2.DefaultCallAdapterFactory$ExecutorCallbackCall$1$1.run(DefaultCallAdapterFactory.java:83)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6718)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

ResultModel.java结果Model.java

package com.example.myapplication;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class ResultModel {

    @SerializedName("error")
    @Expose
    private Boolean error;
    @SerializedName("message")
    @Expose
    private String message;

    public ResultModel(Boolean error, String message) {
        this.error = error;
        this.message = message;
    }

    public Boolean getError() {
        return error;
    }

    public void setError(Boolean error) {
        this.error = error;
    }

    public String getMessage() {
        return message;
    }

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

}

RetrofitClient.java RetrofitClient.java

package com.example.myapplication;

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitClient {

    private  static final String BASE_URL = "https://apitest10101.000webhostapp.com/alaa-apii/public/";
    private static RetrofitClient mInstance;
    private Retrofit retrofit;

    private RetrofitClient(){
        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    public static synchronized RetrofitClient getInstance()
    {
        if(mInstance == null)
        {
            mInstance = new RetrofitClient();
        }
        return mInstance;
    }

    public Api getApi()
    {
        return retrofit.create(Api.class);
    }



}

API interface API接口

package com.example.myapplication;


import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;

public interface Api {


    @FormUrlEncoded
    @POST("createuser")
    Call<ResultModel> createUser(
            @Field("firstname") String firstname,
            @Field("lastname") String lastname,
            @Field("email") String email,
            @Field("password") String password,
            @Field("phone") int phone,
            @Field("region") int region,
            @Field("state") String state,
            @Field("block") String block,
            @Field("street") String street,
            @Field("building") String building,
            @Field("floor") String floor,
            @Field("flat") String flat
    );
}

build gradle构建 gradle

implementation 'com.squareup.retrofit2:retrofit:2.6.2'
implementation 'com.squareup.retrofit2:converter-gson:2.6.2'

the getError() should return false or true and the getMessage() should return the message User Already Exists or User created successfully . getError()应返回 false 或 true,而getMessage()应返回消息User Already ExistsUser created successfully

I use slim framework v3.12 to build api.我使用 slim 框架 v3.12 来构建 api。

** Any suggest ** **任何建议**

Seems like you're getting 422 as http status.好像你得到422作为 http 状态。 Everything that is not a 2XX status code is treated as an error by retrofit and in such cases you access it using response.errorBody() .所有不是2XX状态码的东西都被 retrofit 视为错误,在这种情况下,您可以使用response.errorBody()访问它。

The not so great news is that it has to be manually converted.不太好的消息是它必须手动转换。 One way to do this is using response.errorBody().string() .一种方法是使用response.errorBody().string()

Make sure you call it only once as after the first read it'll no longer be readable.确保只调用一次,因为在第一次读取后它将不再可读。 It's a stream like behaviour.这是类似于 stream 的行为。

The response code you are getting is 422, if this code is agreed upon by the back-end and the front-end that this is not an error, then there is a solution you can do by creating a custom Interceptor and letting it still return the response you get when you get that response code, just make sure to add the Interceptor to your Retrofit client您得到的响应代码是 422,如果后端和前端都同意此代码这不是错误,那么您可以通过创建自定义Interceptor并让它仍然返回来解决当您收到该响应代码时得到的响应,只需确保将Interceptor添加到您的Retrofit client

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM