【问题标题】:Access variable set by Volley's onResponse由 Volley 的 onResponse 设置的访问变量
【发布时间】:2019-01-15 05:45:30
【问题描述】:

我有两个全局变量 currentTempcurrentHum 在调用 Volley 的 onResponse 方法时设置。我的代码如下所示:

// Request a string response from the provided URL.
    private JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, WEATHER_URL, null, new Response.Listener<JSONObject>() {
        public void onResponse(JSONObject response) {
            try {
                JSONObject main = new JSONObject(response.getString("main"));
                currentTemp = main.getString("temp");
                currentHum = main.getString("humidity");
                Log.i("RES", "Temp: " + main.getString("temp") + " Hum: " + main.getString("humidity"));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }}, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(appContext, "An error occurred while retrieving weather info", Toast.LENGTH_LONG).show();
            Log.e("ERR", "ERROR RET WEATHER DATA");
        }
    });


    // Call the OpenWeatherMap API and get data such as temperature and humidity
    private String getWeatherInfo(String key) {
        // Add the request to the RequestQueue to invoke the API
        queue.add(jsonObjectRequest);
        // Access variables set by Volley's onResponse here.
        switch (key) {
            case "temp":
                return String.valueOf(Float.parseFloat(currentTemp) - 273.15);
            case "hum":
                return currentHum;
            default:
                return " ";
        }
    }

我希望能够在调用它的getWeatherInfo 方法中访问由onResponse 方法设置的全局变量的值。然后将值传递给 switch 语句进行处理。如何在不为 currentTempcurrentHum 获取空值的情况下执行此操作?

【问题讨论】:

  • 添加代码说明您如何执行jsonObjectRequest 并调用getWeatherInfo
  • @MJM 我用类似的方式调用 getWeatherInfo:"Its" + getWeatherInfo("temp") + "degrees celsius"

标签: android request android-volley


【解决方案1】:

这项工作旨在通过使用界面来完成。如果您不了解接口回调,请通过this answer。这将帮助您理解界面,并指出这将指导您处理截击响应。

另外,不建议使用全局变量来设置任何响应,而是可以从 volley 类中传递整个 JsonObject。并在您拨打电话的地方解析它。您可以使用 Gson 来解析对您的 ModelArrayList 的响应。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-13
    • 2020-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-31
    • 1970-01-01
    相关资源
    最近更新 更多