Retrofit 2.0 Ошибка синхронного запроса - PullRequest
0 голосов
/ 30 октября 2019

Я пытаюсь реализовать синхронный вызов с помощью модернизации. Я хочу дождаться ответа. У меня есть фрагмент как Loginfrag

public class LoginFrag extends Fragment implements View.OnClickListener {
  @Override
  public void onClick(View v) {
    switch (v.getId()) {
        case R.id.login_button:
            AuthClient auth = new AuthClient();
            try {
                auth.getLogin(email, password);
                responseCode = auth.getResponseCode();
                if (responseCode.equals("1")){
                  startActivity(new Intent(getActivity(), TFActivity.class));
                }
                else{
                     Toast.makeText(getActivity(), "error")  
                }
            catch(Exception e){
                e.PrintStackTrace(); 
            }   

}

Я всегда получаю responseCode как Null. и он выдает исключение нулевого указателя в строке if (responseCode.equals ("1"))

В моем классе AuthClient у меня есть этот код

class AuthClient{

    public void getLogin(String email, String password) throws Exception {
        // constructing header and body
        RetroRequest(headMap, bodyMap);
    }

    private void RetroRequest(HashMap headMap, HashMap bodyMap) {
        MessageReceiver receiver = new MessageReceiver(new Message());

        Intent intent = new Intent(appContext, BackgroundService.class);
        intent.putExtra("headMap", headMap);
        intent.putExtra("bodyMap", bodyMap);
        intent.putExtra("receiver", receiver);
        appContext.startService(intent);
        Log.i(TAG, "RetroRequest: "+ getResponseCode()); // here it logs null
    }

    public class Message {
        public void displayMessage(int resultCode, Bundle resultData) {
            String message  = resultData.getString("message");
            oResponseCode = message;
            setoResponseCode(message);
            // here it logs displayMessage: 1 resp 1
            Log.i(TAG, "displayMessage: " + message + " resp" + oResponseCode);  
    }
}

В моем классе фоновой службы

public class BackgroundService extends IntentService {

public BackgroundService() {
    super("Background Service");

}

@Override
public void onCreate(){
    super.onCreate();
    Log.i("Background Service", "onCreate: Created Background Service");
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {

    ResultReceiver receiver = intent.getParcelableExtra("receiver");
    String url2 = "http://whateverzzzzz.com";

    Bundle extras = intent.getExtras();
    HashMap headMap = (HashMap) extras.getSerializable("headMap");;
    HashMap bodyMap= (HashMap) extras.getSerializable("bodyMap");
    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
    loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

    OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(loggingInterceptor).build();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(url2)
            .addConverterFactory(GsonConverterFactory.create())
            .client(okHttpClient)
            .build();

    RequestCall requestCall = retrofit.create(RequestCall.class);

    Call<JsonObject> call = requestCall.getJSON(headMap, bodyMap);
    try {
        Response<JsonObject> response = call.execute();

        JsonObject posts = response.body();
        Log.i("success ", "onResponse: " + posts.toString());

        JsonParser parser = new JsonParser();
        JsonObject rootObj = parser.parse(posts.toString()).getAsJsonObject();
        JsonObject responseDetails = rootObj
                .getAsJsonObject("resp")
                .getAsJsonObject("respDetails");
       String oResponseCode = responseDetails.get("responseCode").getAsString();
       Bundle bundle = new Bundle();
       bundle.putString("message", oResponseCode);
       receiver.send(1234, bundle);
       //here it logs correct response message
        Log.i("success3 ", "onResponse: " + responseDetails.toString());
    } catch (IOException e) {

    }
}
}

Я перешел с Volley на модернизацию, учитывая, что иногда мне нужно делать синхронные запросы. Я пытаюсь выполнить выполнение в фоновом режиме и вернуть данные обратно во фрагмент. У меня есть другой класс получателей сообщений, который отправляет данные обратно, но код в LoginFrag продолжает выполняться. Спасибо за помощь.

...