簡體   English   中英

如何使用 volley 方法返回 JSONObject? (安卓工作室)

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

我正在制作一個天氣應用程序,我使用天氣 API 和Volley來獲取帶有請求的 JsonObject,然后解析值並在另一個活動(屏幕)中的 textViews 中顯示值。

我現在在我的 MainActivity 中調用此方法,並使用 Intent 將值發送到我的 displayInfo 活動。

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
    }

它現在工作正常,但問題是,現在我想實現觀察者模式,在我的 MainActivity(subject) 中獲取 JsonObject 並讓觀察者(現在為 displayInfo.class)從主題中獲取最新的 JsonObject,所以我需要一個可以在 MainAvtivity 中返回 JSONObject 的方法,我應該怎么做才能為觀察者模式實現這個方法? (不使用內置的觀察者界面)

首先,我建議將您的 getInfoMethod() 放在幫助程序 class 中。 這將允許更容易重用。 接下來,我不會在您的第一個活動中收集您的結果。 相反,我會像您一樣構建 URL。 然后為您的第二個活動創建一個 Intent,並使用 i.putExtra(finalUrl.toString) 將 URL 作為字符串傳遞。 在您的第二個活動中,有一個可見的加載微調器,它在處理結果結束時設置為“消失”。 如果發生錯誤,您可以隨時調用 finish() 將您送回您的第一個活動。

或者,您可以為結果創建 POJO,並使用 Jackson 到 map 將結果轉換為 object。 傳遞一個 object 會更容易,而不是使用 JSONObject 的每一點。 JSONObjects 很好,但是一旦你以你想要的方式獲得數據,你應該 map 到 class 如果你期望使用 object 任何時間長度。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM