首页 > 解决方案 > 从 openWeather api 获取数据不起作用

问题描述

我想从 api 中获取两个数据字段。即:“description”和“temp”。然后将 textView res 设置为显示用户输入的城市的两个参数。但是当我点击应该触发的按钮时jsoup 对象在应用程序中没有任何反应。textView 不可见。所以我不知道执行是否进入 jsonObjectRequest 内部。(顺便说一句:我在清单文件中添加了互联网权限)

MainAcitivity 类:

Button button;
EditText city;
TextView res, debug;

String baseURL = "http://api.openweathermap.org/data/2.5/weather?q=";
String API = "&appid=some_key";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button = findViewById(R.id.button_go);
    city = findViewById(R.id.editText_city);
    res = findViewById(R.id.result);


    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (city.getText().toString() == null) {
                city.setError("Enter city");
                return;
            } else {
                String myURL = baseURL + city.getText().toString() + API;
                //Log.i("URL","URL : "+myURL);


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

                    @Override
                    public void onResponse(JSONObject response) {
                        try {

                            String weather_main = "",id = "";
                            String main_info = response.getString("weather");
                            String temp = response.getString("main");
                            JSONArray jsonArray = new JSONArray(main_info);
                            JSONObject jsonObject = new JSONObject(temp);

                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject weatherObj = jsonArray.getJSONObject(i);
                                //Log.i("ID", "ID:" + weatherObj.getString("id"));
                                //id = weatherObj.getString("id");
                                weather_main = weatherObj.getString("description");

                            }
                           Log.i("Desc", "Description: " + weather_main);
                            Double tempObj = jsonObject.getDouble("temp");
                            res.setText("Weather: " + weather_main+"Temp: "+tempObj);//THIS DOSENT WORK "res" IS INVISIBLE

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                    }

                });

                VolleySingleton.getInstance(MainActivity.this).addToqueue(jsonObjectRequest);
            }

        }
    });

}

VolleySingleton 类:

public VolleySingleton(Context context) {
    mcX = context;
    mRequestQueue = getRequestQueue();
    //mRequestQueue = Volley.newRequestQueue(context.getApplicationContext());

}

public RequestQueue getRequestQueue(){
    if(mRequestQueue == null){
        mRequestQueue = Volley.newRequestQueue(mcX.getApplicationContext());
    }
    return mRequestQueue;
}
public static synchronized VolleySingleton getInstance(Context context){
    if (mInstance == null){
        mInstance = new VolleySingleton(context);
    }
    return mInstance;
}
public void addToqueue(Request req){
    mRequestQueue.add(req);
}

杰森:

    {
  "coord": {
    "lon": -0.13,
    "lat": 51.51
  },
  "weather": [
    {
      "id": 721,enter code here
      "main": "Haze",
      "description": "haze",
      "icon": "50d"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 285.18,
    "feels_like": 282.69,
    "temp_min": 284.82,
    "temp_max": 285.37,
    "pressure": 1011,
    "humidity": 87
  },
  "visibility": 2900,
  "wind": {
    "speed": 3.6,
    "deg": 170
  },
  "clouds": {
    "all": 75
  },
  "dt": 1606298043,
  "sys": {
    "type": 1,
    "id": 1414,
    "country": "GB",
    "sunrise": 1606289744,
    "sunset": 1606319994
  },
  "timezone": 0,
  "id": 2643743,
  "name": "London",
  "cod": 200
}

标签: androidjsonsingletonandroid-volleyopenweathermap

解决方案


像这样创建文件res/xml/network_security_config.xml

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">api.openweathermap.org</domain>
    </domain-config>
</network-security-config>

在你的 AndroidManifest.xml 中:

<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        ...
        android:networkSecurityConfig="@xml/network_security_config"
        ...>
        ...
    </application>
</manifest>

有关更多信息,请阅读


推荐阅读