如何确保函数在调用它的函数完成之后运行?

时间:2019-04-17 20:12:11

标签: java android function

我有一个获取天气数据并将其输出到应用内文本视图的功能。发生这种情况后,我需要更新另一个文本视图(基于天气数据和一些其他变量...),并且我有一个函数可以执行此任务,但是由于我正在执行上一个功能,因此它似乎在运行之前现在就做。处理天气数据的功能称为weatherUpdate,处理第二次文本更新的功能称为textUpdate。我正要在weatherUpdate函数的末尾调用textUpdate函数...

如何确保weatherUpdate完成后运行textUpdate?

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.
}

1 个答案:

答案 0 :(得分:1)

我认为您在错误的地方打电话给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();
        }
    });