Я пытаюсь получить ответ от модифицированного API после регистрации пользователя.
Я получаю нулевое значение от response.body()
function
Регистрационный URL: https://apitest10101.000webhostapp.com/alaa-apii/public/createuser (Метод 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()
должен возвращать сообщение Пользователь уже существует или Пользователь успешно создан .
Я использую Slim Framework v3.12 для сборки API.
** Любое предложение **