MUCHUAN SU
MUCHUAN SU

Reputation: 59

How to return a JSONObject with a method using volley? (android studio)

I am making a weather app where I use a weather API and Volley to get the JsonObject with a request, then parse the values and display the values in textViews in another activity(screen).

I am now calling this method below in my MainActivity and using Intent to send the values to my displayInfo activity.

public void getInfoMethod(){
        String finalUrl ="";
        String cityName = searchBar.getText().toString().trim();
        RequestQueue rQ = Volley.newRequestQueue(getApplicationContext());
        //create a requestQueue to add our request into
        finalUrl = leftApiUrl+cityName+rightApiUrl;

        StringRequest sR = new StringRequest(Request.Method.POST, finalUrl, new Response.Listener<String>() {
            @Override
                public void onResponse(String response) {
                result = "";

                try {
                    JSONObject allJsonRes = new JSONObject(response);

                    String name = allJsonRes.getString("name");
                    double visibility = allJsonRes.getDouble("visibility");
                    int timeZone =allJsonRes.getInt("timezone");
                    //Creates a new JSONArray with values from the JSON string.
                    //try/catch are mandatory when creating JSONObject
                    //now we extract values from this JsonObject
                    JSONArray weatherJsonArr = allJsonRes.getJSONArray("weather");
                    //store []weather
                    //1.to get mainDescription and subDescription
                    //store the []weather part into weatherJsonArr
                    //inside this JsonArray,we store the only JsonObject as weatherBlock
                    //{}0
                    //then get different values from this subJsonObject
                    JSONObject weatherBlock = weatherJsonArr.getJSONObject(0);
                    //this includes id,main,description,icon
                    String mainDescription = weatherBlock.getString("main");
                    //get the string under key "main" e.g. "rain"

                    String subDescription = weatherBlock.getString("description");
                    //e.g."moderate rain"
                    JSONObject mainBlock = allJsonRes.getJSONObject("main");
                    //access {}main
                    double temp_in_C = mainBlock.getDouble("temp");
                    //get temperature from {}main
                    double temp_feel = mainBlock.getDouble("feels_like");
                    double temp_min = mainBlock.getDouble("temp_min");
                    double temp_max = mainBlock.getDouble("temp_max");
                    double pressure = mainBlock.getDouble("pressure");
                    double humidity = mainBlock.getDouble("humidity");
                    JSONObject windBlock = allJsonRes.getJSONObject("wind");
                    //get wind{}
                    double windSpeed = windBlock.getDouble("speed");
                    double degree = windBlock.getDouble("deg");
                    ///
                    JSONObject sysBlock = allJsonRes.getJSONObject("sys");
                    String country = sysBlock.getString("country");
                    ///


                    result += "Current weather in "+ name+", "+country+": "
                            +"\ntime zone: "+ timeZone
                            +"\nvisibility: "+ visibility
                            +"\nTemperature: "+Math.round(temp_in_C)+"°C"
                            +"\n"+mainDescription
                            +"\n("+subDescription+")"
                            +"\nWind speed : "+ windSpeed+" meters per minute"
                            +"\ndegree: "+degree
                            +"\ntemp feel:"+Math.round(temp_feel)+"°C"
                            +"\nmin: "+Math.round(temp_min)+"°C/"+"max"+Math.round(temp_max)+"°C"
                            +"\npressure: "+pressure
                            +"\nhumidity: "+humidity;



                    //then send these values to the displayInfo activity
                    //using Intent and putExtra


                    Intent i =new Intent(MainActivity.this,displayInfo.class);
                    i.putExtra("city",name);
                    i.putExtra("mainD",mainDescription);
                    i.putExtra("subD",subDescription);
                    i.putExtra("temp",temp_in_C);
                    i.putExtra("tempMax",temp_max);
                    i.putExtra("tempMin",temp_min);
                    i.putExtra("tempFeel",temp_feel);
                    i.putExtra("pressure",pressure);
                    i.putExtra("humidity",humidity);
                    i.putExtra("visibility",visibility);
                    i.putExtra("speed",windSpeed);
                    i.putExtra("deg",degree);
                    i.putExtra("timezone",timeZone);
                    startActivity(i);

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener(){
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getApplicationContext(),"Error,check network or spelling",Toast.LENGTH_SHORT).show();
            }//note that .show() is necessary for the message to show
        });
        rQ.add(sR);
        //add the request into the queue,Volley will handle it and send it
        //and then onResponse() or onErrorResponse() will run
        //https://developer.android.com/training/volley/simple
    }

It works fine by now, but the problem is, now I want to implement the observer pattern, get the JsonObject in my MainActivity(subject) and make the observers(displayInfo.class for now) to get the latest JsonObject from subject, so I need a method that could return the JSONObject in the MainAvtivity, what should I do to implement this method for observer pattern? (not using inbuilt Observer interface)

Upvotes: 0

Views: 505

Answers (1)

JonR85
JonR85

Reputation: 728

Firstly I suggest putting your getInfoMethod() in a helper class. This will allow for easier re-usability. Next, I wouldn't gather your result in your first activity. Instead, I would build the URL like you are. Then create an Intent to your second activity and pass the URL as a string with i.putExtra(finalUrl.toString). In your second activity, have a loading spinner visible, that gets set to 'gone' at the end of processing your result. If an error occurs you can always call finish() to send you back to your first activity.

Optionally you could create a POJO for the results and use Jackson to map the results to an object. It'll be easier to pass the one object around instead of working with every little bit of a JSONObject. JSONObjects are fine, but once you have the data the way you want it, you should map it to a class if you are expecting to work with the object for any length of time.

Upvotes: 1

Related Questions