【问题标题】:How to return a JSONObject with a method using volley? (android studio)如何使用 volley 方法返回 JSONObject? (安卓工作室)
【发布时间】:2021-12-30 07:19:07
【问题描述】:

我正在制作一个天气应用程序,我使用天气 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 的方法,我应该如何为观察者模式实现此方法? (不使用内置的观察者接口)

【问题讨论】:

    标签: java json android-studio android-volley observer-pattern


    【解决方案1】:

    首先,我建议将您的 getInfoMethod() 放在帮助程序类中。这将允许更容易重用。 接下来,我不会在您的第一个活动中收集您的结果。相反,我会像你一样构建 URL。然后为您的第二个活动创建一个 Intent,并使用 i.putExtra(finalUrl.toString) 将 URL 作为字符串传递。 在您的第二个活动中,有一个可见的加载微调器,它在处理结果结束时设置为“消失”。如果发生错误,您可以随时调用 finish() 将您送回您的第一个活动。

    您可以选择为结果创建 POJO,并使用 Jackson 将结果映射到对象。传递一个对象会更容易,而不是使用 JSONObject 的每一点。 JSONObjects 很好,但是一旦你以你想要的方式获得数据,你应该将它映射到一个类,如果你希望在任何时间长度内使用该对象。

    【讨论】:

    • 你的意思是不是传递我得到的JSONObject,而是传递URL并用它在第二类中请求?
    • 是的。那就是您正在处理数据。为什么不在那里调用它,而不是尝试传递它。
    • 谢谢,这听起来确实更容易实现观察者模式,并且在进行单元测试时更容易测试这种方法......
    猜你喜欢
    • 1970-01-01
    • 2018-01-29
    • 1970-01-01
    • 1970-01-01
    • 2017-02-09
    • 1970-01-01
    • 2020-10-11
    • 2019-01-21
    • 2019-02-19
    相关资源
    最近更新 更多