사용자 등록 후 개조 API에서 응답을 받으려고합니다.
response.body()
함수 에서 null을 얻습니다.
등록 URL : https://apitest10101.000webhostapp.com/alaa-apii/public/createuser(Method POST)
API는 다음과 같은 단일 객체 JSON을 반환합니다.
{
"error": true,
"message": "User Already Exists"
}
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 문을 제거하면 response.body()
로그에이 오류가 있습니다.
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
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
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 인터페이스
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
);
}
Gradle 빌드
implementation 'com.squareup.retrofit2:retrofit:2.6.2'
implementation 'com.squareup.retrofit2:converter-gson:2.6.2'
는 getError()
false 또는 true getMessage()
를 반환해야 하며 는 User already Exists 또는 User created successfully 메시지를 반환해야합니다 .
슬림 프레임 워크 v3.12를 사용하여 API를 빌드합니다.
** 모든 제안 **
422
http 상태 가 된 것 같습니다 . 2XX
상태 코드 가 아닌 모든 것은 개조에 의해 오류로 처리되며 이러한 경우를 사용하여 액세스합니다 response.errorBody()
.
그리 좋지 않은 소식은 수동으로 변환해야한다는 것입니다. 이를 수행하는 한 가지 방법은 response.errorBody().string()
.
처음 읽은 후에는 더 이상 읽을 수 없으므로 한 번만 호출하십시오. 그것은 행동과 같은 흐름입니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다