一旦收到三个Volley请求,如何显示所有数据

时间:2016-02-26 18:40:04

标签: java android json android-volley

我对Volley有三个请求,我需要同时显示所有三个请求的数据。从两个请求我收到JSONArrays每个我必须制作一个Hashmap>从那两个和第三个请求是我有另一个数据集。我有一个可扩展的视图与适配器设置。什么是最好的方法来找出何时收到所有数据,并可以继续创建一个hashmap并用它更新适配器?

顺便说一下,所有数据都必须显示在新的Fragment中,其中包含第三个响应数据的顶部片段和底部片段以及可扩展的列表视图。

我已经尝试将所有内容添加到SQLite DB中,然后显示其中的所有内容,但它对我来说效果不佳。

public class DBUpdate {

private static DBUpdate dbUpdate = null;
private static String OWMAPIKEY = "&appid=eacc664602550623c7fe93a2732ad127&units=metric";


private DBUpdate() {}


public static DBUpdate getInstance()
{

    if(dbUpdate == null)
    {
        dbUpdate = new DBUpdate();
    }

    return dbUpdate;

}


public boolean updateDaily(String cityId, final Context context){

    String url2 = "http://api.openweathermap.org/data/2.5/forecast/daily?id=" + cityId + OWMAPIKEY;

    System.out.println("DB daily Test 1");

    JsonObjectRequest jorDaily = new JsonObjectRequest(Request.Method.GET, url2 ,null,

            new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {




                    ArrayList<WeatherCondition>  weatherList = new ArrayList<WeatherCondition>();
                    System.out.println("DB daily Test 2");
                    // Trying to extract the imnformation from the JSON response
                    try {
                        JSONObject cityObj = response.getJSONObject("city");
                        JSONObject coordObj = cityObj.getJSONObject("coord");
                        Coordinates coord = new Coordinates(coordObj.getString("lat"),coordObj.getString("lon"));
                        JSONArray list = response.getJSONArray("list");

                        com.example.tadas.betterweather4.City city = new com.example.tadas.betterweather4.City(cityObj.getString("id"),cityObj.getString("name"),cityObj.getString("country"),coord);
                        System.out.println("DB daily Test 3");
                        for (int i = 0; i < list.length(); i++) {

                            String date;
                            String time;

                            JSONObject childJSONObject = list.getJSONObject(i);
                            Calendar calendar = Calendar.getInstance();
                            calendar.setTimeZone(TimeZone.getDefault());
                            calendar.setTimeInMillis(childJSONObject.getInt("dt") * 1000);

                            date = "" + calendar.get(Calendar.YEAR) + "/"+ calendar.get(Calendar.MONTH)+"/"+calendar.get(Calendar.DAY_OF_MONTH);
                            time = calendar.get(Calendar.HOUR_OF_DAY) + ":00";

                            JSONObject tempObj = childJSONObject.getJSONObject("temp");
                            JSONObject weatherObj = childJSONObject.getJSONArray("weather").getJSONObject(0);

                            Wind wind = new Wind(childJSONObject.getString("deg"), childJSONObject.getString("speed"));

                            WeatherCondition w = new WeatherCondition(
                                    weatherObj.getString("icon"),
                                    childJSONObject.getString("humidity")+"%",
                                    "",
                                    weatherObj.getString("description"),
                                    "",
                                    childJSONObject.getString("clouds"),
                                    tempObj.getString("min"),
                                    tempObj.getString("max"),
                                    date,
                                    time,
                                    city,
                                    wind
                            );
                            w.setCurrent("");

                            weatherList.add(w);
                            System.out.println("DB daily Test 4");
                        }

                        DBHelper db = DBHelper.getInstance(context);


                        for (WeatherCondition w: weatherList)
                        {
                            db.insertDaily(w);
                        }



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





                }
            },


            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    System.out.println("DB daily Test 00000000000000");
                }

            }

    );
    System.out.println("DB daily Test end");
    Volley.newRequestQueue(context).add(jorDaily);
    return true;
}

public boolean updateHourly(String cityId, final Context context){
    String url = "http://api.openweathermap.org/data/2.5/forecast?id=" + cityId + OWMAPIKEY;
    JsonObjectRequest jorHourly = new JsonObjectRequest(Request.Method.GET, url,null,

            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {




                    ArrayList<WeatherCondition> weatherList = new ArrayList<WeatherCondition>();

                    // Trying to extract the imnformation from the JSON response
                    try {
                        JSONObject cityObj = response.getJSONObject("city");
                        JSONObject coordObj = cityObj.getJSONObject("coord");
                        Coordinates coord = new Coordinates(coordObj.getString("lat"),coordObj.getString("lon"));
                        JSONArray list = response.getJSONArray("list");

                        com.example.tadas.betterweather4.City city = new com.example.tadas.betterweather4.City(cityObj.getString("id"),cityObj.getString("name"),cityObj.getString("country"),coord);

                        for (int i = 0; i < list.length(); i++) {

                            String date;
                            String time;

                            JSONObject childJSONObject = list.getJSONObject(i);
                            Calendar calendar = Calendar.getInstance();
                            calendar.setTimeZone(TimeZone.getDefault());
                            calendar.setTimeInMillis(childJSONObject.getInt("dt") * 1000);

                            date = "" + calendar.get(Calendar.YEAR) + "/"+ calendar.get(Calendar.MONTH)+"/"+calendar.get(Calendar.DAY_OF_MONTH);
                            time = calendar.get(Calendar.HOUR_OF_DAY) + ":00";

                            JSONObject main = childJSONObject.getJSONObject("main");

                            JSONObject windObj = childJSONObject.getJSONObject("wind");
                            JSONObject cloudsObj = childJSONObject.getJSONObject("clouds");
                            JSONObject rainObj = childJSONObject.getJSONObject("rain");



                            try
                            {
                                JSONObject snowObj = childJSONObject.getJSONObject("snow");
                            }
                            catch (JSONException e)
                            {
                            }

                            String rain = "";
                            try
                            {
                                rain = rainObj.getString("3h");
                            }
                            catch (JSONException e)
                            {
                            }

                            JSONObject weatherObj = childJSONObject.getJSONArray("weather").getJSONObject(0);

                            Wind wind = new Wind(windObj.getString("deg"),windObj.getString("speed"));

                            WeatherCondition w = new WeatherCondition(
                                    weatherObj.getString("icon"),
                                    main.getString("humidity") + "%",
                                    rain,
                                    weatherObj.getString("description"),
                                    "",
                                    cloudsObj.getString("all"),
                                    main.getString("temp_min"),
                                    main.getString("temp_max"),
                                    date,
                                    time,
                                    city,
                                    wind
                            );

                            weatherList.add(w);
                        }

                        DBHelper db = DBHelper.getInstance(context);


                        for (WeatherCondition w: weatherList)
                        {
                            db.insertHourly(w);
                        }



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


                }


            },


            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            }

    );
    Volley.newRequestQueue(context).add(jorHourly);

    return true;
}

public boolean updateCurrent(final String cityId, final Context context){



    String url = "http://api.openweathermap.org/data/2.5/weather?id=" + cityId + OWMAPIKEY;
    JsonObjectRequest jorCurrent = new JsonObjectRequest(Request.Method.GET, url,null,

            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {





                    // Trying to extract the imnformation from the JSON response
                    try {

                        Coordinates coord = new Coordinates(
                                response.getJSONObject("coord").getString("lat"),
                                response.getJSONObject("coord").getString("lon"));

                        com.example.tadas.betterweather4.City city = new com.example.tadas.betterweather4.City(
                                response.getString("id"),
                                response.getString("name"),
                                response.getJSONObject("sys").getString("country"),
                                coord
                        );



                            String date;
                            String time;


                            Calendar calendar = Calendar.getInstance();
                            calendar.setTimeZone(TimeZone.getDefault());
                            calendar.setTimeInMillis(response.getInt("dt") * 1000);

                            date = "" + calendar.get(Calendar.YEAR) + "/"+ calendar.get(Calendar.MONTH)+"/"+calendar.get(Calendar.DAY_OF_MONTH);
                            time = calendar.get(Calendar.HOUR_OF_DAY) + ":00";

                            Wind wind = new Wind(
                                    response.getJSONObject("wind").getString("deg"),
                                    response.getJSONObject("wind").getString("speed")
                            );
                        String rain = "";
                            try{
                                rain = response.getJSONObject("rain").getString("3h")+ "mm";
                            }
                            catch (Exception e)
                            {

                            }
                        String snow = "";
                        try{
                            rain = response.getJSONObject("snow").getString("3h");
                        }
                        catch (Exception e)
                        {

                        }

                            WeatherCondition w = new WeatherCondition(
                                    response.getJSONArray("weather").getJSONObject(0).getString("icon"),
                                    response.getJSONObject("main").getString("humidity") + "%",
                                    rain,
                                    response.getJSONArray("weather").getJSONObject(0).getString("description"),
                                    snow,
                                    response.getJSONObject("clouds").getString("all"),
                                    response.getJSONObject("main").getString("temp_min"),
                                    response.getJSONObject("main").getString("temp_max"),
                                    date,
                                    time,
                                    city,
                                    wind
                            );



                        DBHelper db = DBHelper.getInstance(context);

                        w.setCurrent(response.getJSONObject("main").getString("temp"));

                        db.insertCurrent(w);


                        List<WeatherCondition> list = DBHelper.getInstance(context).getAllDaily(cityId);
                        for(WeatherCondition wd: list)
                        {
                            System.out.println(wd.getMaxTemp());
                        }

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


                }


            },


            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            }

    );
    Volley.newRequestQueue(context).add(jorCurrent);

    return true;
}

}

2 个答案:

答案 0 :(得分:2)

另一种方式是(特别是如果你的请求彼此依赖),使请求顺序,即在另一个之后。

当您在onResponse()方法中收到第一个请求的回复时,请从那里发出第二个请求。然后从第二个请求的onResponse()发出第三个请求。最后,您可以在调用第三个请求onResponse()时继续更新UI,因为您已经知道前两个请求已成功完成。

另一个好处是,如果任何请求失败,那么您可以直接停在那里,而无需提出下一个请求。

答案 1 :(得分:1)

我有类似的情况,我使用布尔来跟踪请求的完成情况。我使用了以下过程,它对我有用 -

  1. 初始化布尔值isData1Ready = isData2Ready = isData3Ready to 假;
  2. 当每个请求返回时,将布尔值设置为true 与数据
  3. 然后我写了一个检查所有值的方法 是真的
  4. 只有当所有3个值都为真时,才会继续更新 UI
  5. 希望这有帮助!