代码之家  ›  专栏  ›  技术社区  ›  Nikhil Raghavendra

由Volley的onResponse设置的访问变量

  •  0
  • Nikhil Raghavendra  · 技术社区  · 7 年前

    我有两个全局变量 currentTemp currentHum 当截击结束时设定的 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 调用它的方法。然后将这些值传递给switch语句进行处理。如何在不获取空值的情况下执行 电流温度 ?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Khemraj Sharma    7 年前

    这项工作是通过使用一个接口来完成的。如果您不知道接口回调,请通过 this answer 。这将有助于您理解界面,并有助于指导您处理截击反应。

    此外,不建议使用全局变量来设置任何响应,而是可以传递整个响应 JsonObject 截击课。然后在你打电话的地方分析它。你可以用 Gson 用于解析对 Model ArrayList .