Как я могу убедиться, что функция запускается ПОСЛЕ функции, которая вызывает ее, завершена?

1

У меня есть функция, которая получает некоторые данные о погоде и выводит их в приложение для просмотра текста в приложении. Мне нужно обновить другое представление текста после того, как это произошло (на основе данных о погоде и некоторых других переменных...), и у меня есть функция, которая выполняет эту задачу, но, кажется, она запускается до завершения предыдущей функции, так как я делаю это сейчас. Функция, имеющая дело с данными о погоде, называется weatherUpdate, функция, которая имеет дело со вторым обновлением текста, называется textUpdate. Я вызываю функцию textUpdate прямо в конце функции weatherUpdate...

Как я могу убедиться, что textUpdate запускается после того, как WeatherUpdate закончится?

void weatherUpdate() {
    //Weather API url and key
    String apiURL = "https://api.openweathermap.org/data/2.5/weather?lat=00.0000&lon=00.0000&units=metric&APPID=00000000000000000000000000000000";
    //Request JSON data from weather API
    RequestQueue queue = Volley.newRequestQueue(this);
    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, apiURL, null, new Response.Listener<JSONObject>() {
        //Parse data to get temperature
        @Override
        public void onResponse(JSONObject response) {
            try {
                //Get temperature data, format it to 1 decimal place, and output in the text box.
                temp1 = (response.getJSONObject("main").getDouble("temp"));
                String tempFormatted = (getString(R.string.temp_format, temp1));
                tempBox.setText(tempFormatted);
                //get the icon for weather conditions.
                String iconName = response.getJSONArray("weather").getJSONObject(0).getString("icon");
                String imageURL = String.format("http://openweathermap.org/img/w/%1s.png", iconName);
                Glide.with(MainActivity.this).load(imageURL).into(weatherImage);
            } catch (JSONException e) {
                //catch errors and toast error message.
                e.printStackTrace();
                Toast errorToast = Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG);
                errorToast.show();
            }
        }
        //Request error handler
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast errorToast = Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_LONG);
            errorToast.show();
        }
    });
    queue.add(request);
    //Toast notification that update has run.
    Toast.makeText(MainActivity.this, "Weather Updated!", Toast.LENGTH_SHORT).show();
    textUpdate(); //<-this is where my problem is. It seems to run before the above is finished.
}
Теги:
function

1 ответ

0

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

    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, apiURL, null, new Response.Listener<JSONObject>() {
        //Parse data to get temperature
        @Override
        public void onResponse(JSONObject response) {
            try {
                //Get temperature data, format it to 1 decimal place, and output in the text box.
                temp1 = (response.getJSONObject("main").getDouble("temp"));
                String tempFormatted = (getString(R.string.temp_format, temp1));
                tempBox.setText(tempFormatted);
                //get the icon for weather conditions.
                String iconName = response.getJSONArray("weather").getJSONObject(0).getString("icon");
                String imageURL = String.format("http://openweathermap.org/img/w/%1s.png", iconName);
                Glide.with(MainActivity.this).load(imageURL).into(weatherImage);
                textUpdate();
            } catch (JSONException e) {
                //catch errors and toast error message.
                e.printStackTrace();
                Toast errorToast = Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG);
                errorToast.show();
            }
        }
        //Request error handler
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast errorToast = Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_LONG);
            errorToast.show();
        }
    });

Ещё вопросы

Сообщество Overcoder
Наверх
Меню