【问题标题】:not able to fetch JSON Data in android Weather application无法在 android Weather 应用程序中获取 JSON 数据
【发布时间】:2021-03-20 17:51:23
【问题描述】:

我无法通过 volley 获取 json。我正在从开放天气 api 获取数据。

这里是代码

我已尝试获取数据,但没有收到响应。

       currentTemperatureField = 
         (TextView)findViewById(R.id.current_temperature_field);
    String url = "http://api.openweathermap.org/data/2.5/weather? 
    q=bangalore,IN&appid=899bd4a7869e57cdaac65346d0659463";

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
            (Request.Method.GET, url, null, new 
            Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    currentTemperatureField.setText("Response: " + response.toString());
                    try{
                        JSONObject mainJSONObject = response.getJSONObject("main");
                        String temp = mainJSONObject.getString("temp");
                        currentTemperatureField.setText(temp);
                        Log.v("WEETHER","Response: " + response.toString());
                    }
                    catch(Exception e){
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    // TODO: Handle error

                }
            });

【问题讨论】:

  • 你有什么错误吗?

标签: android json android-volley weather


【解决方案1】:

如果您检查 API 的响应,“temp”似乎返回 Double 类型的值。

改变这一行

String temp = mainJSONObject.getString("temp");

double temp = mainJSONObject.getDouble("temp");

因此更改下面的行

currentTemperatureField.setText(temp);

currentTemperatureField.setText(String.valueOf(temp));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-20
    • 2019-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多