#android #json #retrofit2
Вопрос:
Запрос post на сервер работает правильно, так как регистратор okhttp печатает именно тот json, который я хотел, но обратный вызов дооснащения не выполняется. Я не знаю, почему это происходит, может ли кто-нибудь помочь. Это мой метод отправки запроса на сервер
private void loginUser() {
custPrograssbar.prograssCreate(LoginActivity.this);
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("mobile", edUsername.getText().toString());
jsonObject.put("password", edPassword.getText().toString());
jsonObject.put("imei", Utiles.getIMEI(LoginActivity.this));
JsonParser jsonParser = new JsonParser();
Log.d("callforlogin",jsonObject.toString());
Call<JsonElement> call = APIClient.getInterface().getLogin((JsonObject) jsonParser.parse(jsonObject.toString()));
GetResult getResult = new GetResult();
getResult.setMyListener(this);
getResult.callForLogin2(call, "1");
} catch (JSONException e) {
e.printStackTrace();
}
}
а вот и обратный звонок
@Override
public void callback(JsonObject result, String callNo) {
try {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
// Do something after 5s = 5000ms
if (callNo.equalsIgnoreCase("1")) {
custPrograssbar.closePrograssBar();
Gson gson = new Gson();
// Gson gson = new GsonBuilder().setLenient().create();
if(result != null) {
LoginUser response = gson.fromJson(result.toString(), LoginUser.class);
Log.d("testlogin", "testing" response.getResponseMsg());
if (response.getResult().equals("true")) {
sessionManager.setUserDetails("", response.getUser());
sessionManager.setBooleanData(login, true);
OneSignal.sendTag("userId", response.getUser().getId());
startActivity(new Intent(LoginActivity.this, HomeActivity.class));
finish();
}
}
else
{
// Toast.makeText(this, "null reslut recived", Toast.LENGTH_SHORT).show();
Log.d("testlog","null result receive");
}
}
}
}, 2000);
} catch (Exception e) {
Log.e("error from this"," --> " e.toString());
e.printStackTrace();
}
}
Это мой регистратор httpclient
021-09-04 09:57:35.165 19094-19266/com.freshmeatfood D/OkHttp: {"user":{"id":"22","name":"RITURAJ SAHA d","imei":"87c05e1cc687a845","email":"rituraj10saha@gmail.com","ccode":" 91","mobile":"9674345373","rdate":"2021-09-02 22:05:36","password":"abc","status":"1","wallet":"0","pin":null,"code":"353474","refercode":"0"},"d_charge":null,"ResponseCode":"200","Result":"true","ResponseMsg":"Login successfully!"}
это мой класс моделей
package com.freshmeatfood.model;
import com.google.gson.annotations.SerializedName;
@SuppressWarnings("unused")
public class LoginUser {
@SerializedName("user")
private User mUser;
@SerializedName("d_charge")
private int dCharge;
@SerializedName("ResponseCode")
private String mResponseCode;
@SerializedName("Result")
private String mResu<
@SerializedName("ResponseMsg")
private String mResponseMsg;
public int getdCharge() {
return dCharge;
}
public void setdCharge(int dCharge) {
this.dCharge = dCharge;
}
public String getResponseCode() {
return mResponseCode;
}
public void setResponseCode(String responseCode) {
mResponseCode = responseCode;
}
public String getResponseMsg() {
return mResponseMsg;
}
public void setResponseMsg(String responseMsg) {
mResponseMsg = responseMsg;
}
public String getResult() {
return mResu<
}
public void setResult(String result) {
mResult = resu<
}
public User getUser() {
return mUser;
}
public void setUser(User user) {
mUser = user;
}
}
this is my listnerclass
package com.freshmeatfood.retrofit;
import android.util.Log;
import android.widget.Toast;
import com.freshmeatfood.MyApplication;
import com.freshmeatfood.model.LoginUser;
import com.freshmeatfood.utils.Utiles;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class GetResult {
public static MyListener myListener;
public void callForLogin(Call<JsonObject> call, String callno) {
//my inject
// if(callno.equals("1")) {
// Gson gson = new Gson();
// // LoginUser response = gson.fromJson(call.toString(), LoginUser.class);
// Log.d("callforlogin", " " call.getClass() " " callno "");
// }
if(!Utiles.internetChack()){
Toast.makeText(MyApplication.mContext, "Please Check Your Internet Connection", Toast.LENGTH_SHORT).show();
}else {
call.enqueue(new Callback<JsonObject>() {
@Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
Log.e("message", " : " response.message());
Log.e("body", " : " response.body());
Log.e("callno", " : " callno);
Log.d("callforlogin","success " call);
myListener.callback(response.body(), callno);
}
@Override
public void onFailure(Call<JsonObject> call, Throwable t) {
myListener.callback(null, callno);
call.cancel();
Log.d("callforlogin","failed " call " " t.getMessage());
t.printStackTrace();
}
});
}
}
public void callForLogin2(Call<JsonElement> call, String callno) {
//my inject
// if(callno.equals("1")) {
// Gson gson = new Gson();
// // LoginUser response = gson.fromJson(call.toString(), LoginUser.class);
// Log.d("callforlogin", " " call.getClass() " " callno "");
// }
if(!Utiles.internetChack()){
Toast.makeText(MyApplication.mContext, "Please Check Your Internet Connection", Toast.LENGTH_SHORT).show();
}else {
call.enqueue(new Callback<JsonElement>() {
@Override
public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
Log.e("message", " : " response.message());
Log.e("body", " : " response.body());
Log.e("callno", " : " callno);
Log.d("callforlogin","success " call);
myListener.callback((JsonObject) response.body(), callno);
}
@Override
public void onFailure(Call<JsonElement> call, Throwable t) {
myListener.callback(null, callno);
call.cancel();
Log.d("callforlogin","failed " call " " t.getMessage());
t.printStackTrace();
}
});
}
}
public interface MyListener {
// you can define any parameter as per your requirement
public void callback(JsonObject result, String callNo);
}
public void setMyListener(MyListener Listener) {
myListener = Listener;
}
}
here on failure is triggered and the error message is
2021-09-04 09:57:35.171 19094-19094/com.freshmeatfood D/callforlogin: failed retrofit2.DefaultCallAdapterFactory$ExecutorCallbackCall@b2d3090 Expected value at line 2 column 5 path $
this is Api client
package com.freshmeatfood.retrofit;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class APIClient {
static Retrofit retrofit = null;
//public static String baseUrl = "http://hungrygrocerydelivery.cscodetech.com/";
// public static String baseUrl = "https://gueztunewapp.centurianapps.com";
public static String baseUrl = "http://admin.gueztuapp.com";
public static final String APPEND_URL = "/api/";
public static UserService getInterface() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.build();
//my inject
Gson gson = new GsonBuilder().setLenient().create();
//
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
// .addConverterFactory(GsonConverterFactory.create()) //**prev
.addConverterFactory(GsonConverterFactory.create(gson))
.client(client)
.build();
return retrofit.create(UserService.class);
}
}