酷欧天气无法显示天气

CheapTalking 2017-10-09 09:15:14
我刚学Android不久,就照着第一行代码敲了一个欧酷天气。运行以后点击具体的一个城市,没有显示天气情况,想了一天没什么头绪。我贴一下代码,麻烦大家帮瞧瞧!

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.coolweather.com.coolweather">

<uses-permission android:name="android.permission.INTERNET" />

<application
android:name="org.litepal.LitePalApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".WeatherActivity"></activity>
</application>

</manifest>

public class Province extends DataSupport {
//LitePal中的每一个实体类都要继承DataSupport
private int id;//每个实体类都有的字段
private String provinceName;//省的名字
private int provinceCode;//省的代号

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getProvinceName() {
return provinceName;
}

public void setProvinceName(String provinceName) {
this.provinceName = provinceName;
}

public int getProvinceCode() {
return provinceCode;
}

public void setProvinceCode(int provinceCode) {
this.provinceCode = provinceCode;
}
}


public class City extends DataSupport {
private int id;
private String cityName;//市的名字
private int cityCode;//市的代号
private int provinceId;//当前市所属省的id值

public void setId(int id) {
this.id = id;
}

public int getId() {
return id;
}

public String getCityName() {
return cityName;
}

public void setCityName(String cityName) {
this.cityName = cityName;
}

public int getCityCode() {
return cityCode;
}

public void setCityCode(int cityCode) {
this.cityCode = cityCode;
}

public int getProvinceId() {
return provinceId;
}

public void setProvinceId(int provinceId) {
this.provinceId = provinceId;
}
}


public class County extends DataSupport {
private int id;
private String countyName;//县的名字
private String weatherId;//县所对应的天气id
private int cityId;//当前所属市的id

public void setId(int id) {
this.id = id;
}

public int getId() {
return id;
}

public void setCountyName(String countyName) {
this.countyName = countyName;
}

public String getCountyName() {
return countyName;
}

public void setWeatherId(String weatherId) {
this.weatherId = weatherId;
}

public String getWeatherId() {
return weatherId;
}

public void setCityId(int cityId) {
this.cityId = cityId;
}

public int getCityId() {
return cityId;
}
}

public class AQI {
public AQICity city;

public class AQICity{
public String aqi;
public String pm25;
}
}


public class Basic {
/*由于用GSON解析出来的变量名不够友好
我们需要使用SerializedName来让GSON解析出来的变量名与实体类定义出来的变量名一一对应
也可以说是让JSON字段与Java字段建立映射关系*/
@SerializedName("city")
public String cityName;
@SerializedName("id")
public String weatherId;

public Update update;

public class Update{
@SerializedName("loc")
public String updateTime;
}

}


public class Forecast {
public String date;
@SerializedName("tmp")
public Temperature temperature;
@SerializedName("cond")
public More more;

public class Temperature{
public String max;
public String min;
}

public class More{
@SerializedName("txt_d")
public String info;
}
}


public class Now {
@SerializedName("tmp")
public String temperature;
@SerializedName("cond")
public More more;
public class More{
@SerializedName("txt")
public String info;
}
}


public class Suggestion {
@SerializedName("comf")
public Comfort comfort;
@SerializedName("cw")
public CarWash carWash;
public Sport sport;

public class Comfort{
@SerializedName("txt")
public String info;
}

public class CarWash{
@SerializedName("txt")
public String info;
}

public class Sport{
@SerializedName("txt")
public String info;
}
}


public class Weather {
public String status;
public Basic basic;
public AQI aqi;
public Now now;
public Suggestion suggestion;

//因为daily_forecast是数组,要用List集合引用Forecast
@SerializedName("daily_forecast")
public List<Forecast> forecastList;
}


public class HttpUtil {
//处理请求,和服务器交互
public static void sendOkHttpRequest(String address, okhttp3.Callback callback){
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(address).build();
client.newCall(request).enqueue(callback);
}
}


...全文
323 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
YXTS122 2021-02-09
  • 打赏
  • 举报
回复
这个代码我也一直没有运行起来呀!不知道咋回事
CheapTalking 2021-02-06
  • 打赏
  • 举报
回复
出问题建议DEBUG查找出错原因,这个代码贴的还是挺硬核的哈哈
ycxy555 2020-07-04
  • 打赏
  • 举报
回复
引用 5 楼 qq_42932427 的回复:
[quote=引用 4 楼 ycxy555的回复:]我是第三阶段跳不过去
我也是,楼主解决了吗[/quote] 搞定了
qq_42932427 2020-05-27
  • 打赏
  • 举报
回复
引用 4 楼 ycxy555的回复:
我是第三阶段跳不过去
我也是,楼主解决了吗
ycxy555 2020-05-12
  • 打赏
  • 举报
回复
我是第三阶段跳不过去
CheapTalking 2017-10-09
  • 打赏
  • 举报
回复
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this); if (pref.getString("weather",null) != null){ Intent intent = new Intent(MainActivity.this,WeatherActivity.class); startActivity(intent); finish(); } } }
CheapTalking 2017-10-09
  • 打赏
  • 举报
回复
public class ChooseAreaFragment extends Fragment { public static final int LEVEL_PROVINCE = 0; public static final int LEVEL_CITY = 1; public static final int LEVEL_COUNTY = 2; private ProgressDialog progressDialog; private TextView titleText; private Button backButton; private ListView listView; private ArrayAdapter<String> adapter; private List<String> dataList = new ArrayList<>(); //省列表 private List<Province> provinceList; //市列表 private List<City> cityList; //县列表 private List<County>countyList; //选中的省份 private Province selectedProvince; //选中的城市 private City selectedCity; //当前选中的级别 private int currentLevel; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.choose_area,container,false); titleText = (TextView)view.findViewById(R.id.title_text); backButton = (Button)view.findViewById(R.id.back_button); listView = (ListView)view.findViewById(R.id.list_view); adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1,dataList); listView.setAdapter(adapter); return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (currentLevel == LEVEL_PROVINCE){ selectedProvince = provinceList.get(position); queryCities(); }else if (currentLevel == LEVEL_CITY){ selectedCity = cityList.get(position); queryCounties(); }else if (currentLevel == LEVEL_COUNTY){ String weatherId = countyList.get(position).getWeatherId(); Intent intent = new Intent(getActivity(), WeatherActivity.class); intent.putExtra("weather_id",weatherId); startActivity(intent); getActivity().finish(); } } }); backButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (currentLevel == LEVEL_COUNTY){ queryCities(); }else if (currentLevel == LEVEL_CITY){ queryProvinces(); } } }); queryProvinces(); } //查询全国所有的省,优先从数据库查,如果没有查到再到数据库上查 private void queryProvinces() { titleText.setText("中国"); backButton.setVisibility(View.GONE); provinceList = DataSupport.findAll(Province.class); if (provinceList.size() > 0) { dataList.clear(); for (Province province : provinceList) { dataList.add(province.getProvinceName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); currentLevel = LEVEL_PROVINCE; }else { String address = "http://guolin.tech/api/china"; queryFromServer(address,"province"); } } //查询省内所有的市,优先从数据库查,如果没有查到再到数据库上查 private void queryCities() { titleText.setText(selectedProvince.getProvinceName()); backButton.setVisibility(View.VISIBLE); cityList = DataSupport.where("provinceid=?",String.valueOf(selectedProvince.getId())).find(City.class); if (cityList.size() > 0){ dataList.clear(); for (City cities : cityList) { dataList.add(cities.getCityName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); currentLevel = LEVEL_CITY; }else { int provinceCode = selectedProvince.getProvinceCode(); String address = "http://guolin.tech/api/china/" + provinceCode; queryFromServer(address,"city"); } } //查询市内所有的县,优先从数据库查,如果没有查到再到数据库上查 private void queryCounties() { titleText.setText(selectedCity.getCityName()); backButton.setVisibility(View.VISIBLE); countyList = DataSupport.where("cityid=?",String.valueOf(selectedCity.getId())).find(County.class); if (countyList.size() > 0){ dataList.clear(); for (County counties : countyList){ dataList.add(counties.getCountyName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); currentLevel = LEVEL_COUNTY; }else { int provinceCode = selectedProvince.getProvinceCode(); int cityCode = selectedCity.getCityCode(); String address = "http://guolin.tech/api/china/" + provinceCode + "/" + cityCode; queryFromServer(address,"city"); } } //根据传入的地址和类型从服务器上查询省市县数据 private void queryFromServer(String address, final String type) { showProgressDialog(); HttpUtil.sendOkHttpRequest(address, new Callback() { @Override public void onFailure(Call call, IOException e) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { closeProgressDialog(); Toast.makeText(getContext(),"加载失败",Toast.LENGTH_SHORT).show(); } }); } @Override public void onResponse(Call call, Response response) throws IOException { String responseText = response.body().string(); boolean result = false; if ("province".equals(type)){ result = Utility.handleProvinceResponse(responseText); }else if ("city".equals(type)){ result = Utility.handleCityResponse(responseText,selectedProvince.getId()); }else if ("county".equals(type)){ result = Utility.handleCountyResponse(responseText,selectedCity.getId()); } if (result){ getActivity().runOnUiThread(new Runnable() { @Override public void run() { closeProgressDialog(); if ("province".equals(type)){ queryProvinces(); }else if ("city".equals(type)){ queryCities(); }else if ("county".equals(type)){ queryCounties(); } } }); } } }); } //显示进度对话框 private void showProgressDialog(){ if (progressDialog == null){ progressDialog = new ProgressDialog(getContext()); progressDialog.setMessage("正在加载...."); progressDialog.setCanceledOnTouchOutside(false); } progressDialog.show(); } //关闭进度对话框 private void closeProgressDialog(){ if (progressDialog != null){ progressDialog.dismiss(); } } }
CheapTalking 2017-10-09
  • 打赏
  • 举报
回复
public class Utility { //解析和处理服务器返回的省级数据 public static boolean handleProvinceResponse(String response){ if (!TextUtils.isEmpty(response)){ try { //先使用JSONArray和JSONObject解析数据 //即接受返回的数据用数组装起来 JSONArray allProvinces = new JSONArray(response); for (int i=0; i<allProvinces.length(); i++){ //再逐个拆解 JSONObject provinceObject = allProvinces.getJSONObject(i); //然后组装成实体类对象 Province province = new Province(); province.setProvinceName(provinceObject.getString("name")); province.setProvinceCode(provinceObject.getInt("id")); //在调用save()方法将数据存储到数据库里 province.save(); } return true; } catch (JSONException e) { e.printStackTrace(); } } return false; } //解析和处理服务器返回的市级数据 public static boolean handleCityResponse(String response, int provinceId){ if (!TextUtils.isEmpty(response)){ try { JSONArray allCities = new JSONArray(response); for (int i=0; i<allCities.length(); i++){ JSONObject cityObject = allCities.getJSONObject(i); City city = new City(); city.setCityName(cityObject.getString("name")); city.setCityCode(cityObject.getInt("id")); city.setProvinceId(provinceId); city.save(); } return true; } catch (JSONException e) { e.printStackTrace(); } } return false; } //解析和处理服务器返回的县级数据 public static boolean handleCountyResponse(String response, int cityId){ if (!TextUtils.isEmpty(response)){ try { JSONArray allCounties = new JSONArray(response); for (int i=0; i<allCounties.length(); i++){ JSONObject countyObject = allCounties.getJSONObject(i); County county = new County(); county.setCountyName(countyObject.getString("name")); county.setWeatherId(countyObject.getString("weather_id")); county.setCityId(cityId); county.save(); } return true; } catch (JSONException e) { e.printStackTrace(); } } return false; } //将返回的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; } }

80,356

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧