0

I have two global variables currentTemp and currentHum that are set when Volley's onResponse method is called. My code looks like this:

// 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 " ";
        }
    }

I want to be able to access the values of the global variables set by the onResponse method in the getWeatherInfo method that invoked it. Then pass the values to a switch statement for processing. How do I do it without getting empty values for currentTemp and currentHum?

Nikhil Raghavendra
  • 1,570
  • 5
  • 18
  • 25

1 Answers1

0

This work is meant to be done with use of an interface. If you don't know about an interface callbacks then please go through this answer. Which will help you understand interface, and plus point that this will guide you for handling volley response.

Also this is not recommended to take global variables to set any response, rather you can pass your whole JsonObject from volley class. and parse it where you make a call. You can use Gson for parsing the response to your Model or ArrayList.

Khemraj Sharma
  • 57,232
  • 27
  • 203
  • 212