《1》java.lang.NoSuchMethodError: No virtual method getContext()
错误的地方:
adapter = new ArrayAdapter<>(getContext(),android.R.layout.simple_list_item_1,dataList);
解决办法:
出现 java.lang.NoSuchMethodError: No virtual method getContext(),最后找到的原因是因为版本的问题,AVD上我是android7.1,但是魅族只有5.1(API22),
getContext() 是出现在API23以后才有的,所以改为使用getActivity()就可以解决。
Logcat:
06-04 10:40:58.949 20009-20009/com.example.wzhworld.mycoolweather E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.wzhworld.mycoolweather, PID: 20009
java.lang.NoSuchMethodError: No virtual method getContext()Landroid/content/Context; in class Lcom/example/wzhworld/mycoolweather/service/ChooseAreaFragment; or its super classes (declaration of 'com.example.wzhworld.mycoolweather.service.ChooseAreaFragment' appears in /data/app/com.example.wzhworld.mycoolweather-2/split_lib_slice_0_apk.apk)
at com.example.wzhworld.mycoolweather.service.
ChooseAreaFragment.onCreateView(ChooseAreaFragment.
java:69)
《2》获取天气信息失败
天气接口
Weather.java
String weatherUrl = "http://guolin.tech/api/weather?cityid=" + weatherId + "&key=bc0418b57b2d4918819d3974ac1285d9";
访问和风天气的API获取的JSON格式
{"HeWeather": [{"basic":{"cid":"CN101190401","location":"苏州","parent_city":"苏州","admin_area":"江苏","cnty":"中国","lat":"31.29937935","lon":"120.61958313","tz":"+8.00","city":"苏州","id":"CN101190401","update":{"loc":"2018-05-09 09:47","utc":"2018-05-09 01:47"}},"update":{"loc":"2018-05-09 09:47","utc":"2018-05-09 01:47"},"status":"ok","now":{"cloud":"3","cond_code":"100","cond_txt":"晴","fl":"19","hum":"64","pcpn":"0.0","pres":"1019","tmp":"19","vis":"20","wind_deg":"42","wind_dir":"东北风","wind_sc":"2","wind_spd":"7","cond":{"code":"100","txt":"晴"}},"daily_forecast":[{"date":"2018-05-09","cond":{"txt_d":"晴"},"tmp":{"max":"25","min":"15"}},{"date":"2018-05-10","cond":{"txt_d":"多云"},"tmp":{"max":"25","min":"16"}},{"date":"2018-05-11","cond":{"txt_d":"多云"},"tmp":{"max":"27","min":"21"}}],"aqi":{"city":{"aqi":"71","pm25":"51","qlty":"良"}},"suggestion":{"comf":{"type":"comf","brf":"舒适","txt":"白天不太热也不太冷,风力不大,相信您在这样的天气条件下,应会感到比较清爽和舒适。"},"sport":{"type":"sport","brf":"较适宜","txt":"天气较好,户外运动请注意防晒。推荐您进行室内运动。"},"cw":{"type":"cw","brf":"较适宜","txt":"较适宜洗车,未来一天无雨,风力较小,擦洗一新的汽车至少能保持一天。"}}}]}
接着又报错
org.json.JSONException: Value Request of type java.lang.String cannot be con
Utility.java
原先:
JSONArray jsonArray = jsonObject.getJSONArray("HeWeather data service 3.0");
应改为,与返回的JSON格式头部一致
/**
* 将返回的JSON数据解析成Weather实体类
*/
public static Weather handleWeatherResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("HeWeather");
String weatherContent = jsonArray.getJSONObject(0).toString();
return new Gson().fromJson(weatherContent, Weather.class);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
终于可以运行了,接下来我要自己敲一遍,消化为自己的东西。