Выполнять асинхронный вызов c последовательно с сервера android java - PullRequest
0 голосов
/ 18 апреля 2020

все. Я все еще новичок в android, и у меня есть вопрос. У меня есть activity, что я сделал звонок на сервер AWS. Я использую два разных метода get, и один вызов должен ждать, пока другие вызовы не завершатся sh. Я пытался сделать с AsyncTask, но я думаю, что я делаю не так. Как мне достичь своей цели?

Вот мой код:

@Override
public void onStart() {
    super.onStart();
    JSONObject obj = new JSONObject();
    try {
        //first call
        obj.put("id", this.ID);
        conn.apiCall(Connector.GET_CATEGORY, obj.toString(), new String[]{Integer.toString(this.ID)});
    }
    catch (Exception e) { }
}

@Override
public void onData(int type, String data) {
    super.onData(type, data);

    if (type == Connector.GET_CATEGORY) {
        try {
            JSONObject obj = new JSONObject(data);
            JSONArray arr = obj.getJSONArray("Items");

            for (int i = 0; i < arr.length(); i++) {
                this.location = arr.getJSONObject(i).getInt("cityCode");
                //Second call. To complete first call, second call needs to finish first
                getCity();
            }
        }
        catch (Exception e) {}
    }
    else if (type == Connector.CITY) {
        try {
            JSONObject obj =  new JSONObject(data);
            JSONArray arr = obj.getJSONArray("location");

            for (int i = 0; i < arr.length(); i++) {
                if (arr.getJSONObject(i).getInt("id") == this.location)
                    this.city = arr.getJSONObject(i).getString("name");
            }
        }
        catch (Exception e) {}
    }
     else {}
}

    private void getCity() {
    AsyncTask x = new AsyncTask() {
        @Override
        protected Object doInBackground(Object[] objects) {
            return null;
        }
        @Override
        protected void onPreExecute() {
            conn.apiCall(Connector.CITY);
        }
    };
    try {
        x.execute().get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
}
...