第一行代码-第二版的酷欧天气
- 首先创建数据库类继承LitePal,用来存储城市数据
- Province.java
public class Province extends DataSupport { private int id; private String provinceName; private int provinceCode; ...//getter and setter
}
- City.java
public class City extends DataSupport {
private int id;
private String CityName;
private int cityCode;
private int provinceId;
...//getter and setter
}
- County.java
public class County extends DataSupport {
private int id;
private String countyName;
private String weatherId;
private int cityId;
...//getter and setter
}
- 创建选择城市的ChooseAreaFragment.java
public class ChooseAreaFragment extends Fragment {
private static final String TAG = "ChooseAreaFragment";
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
private List
//省列表
private List
// 市列表
private List
//县列表
private List
//选中的省份
private Province selectedProvice;
//选中的城市
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.fragment_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<>(getContext(), android.R.layout.simple_list_item_1,dataList);
listView.setAdapter(adapter);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//初始化省级数据
queryProvince();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView> adapterView, View view, int position, long id) {
if (currentLevel == LEVEL_PROVINCE) {
selectedProvice = provinceList.get(position);
queryCity();
} else if (currentLevel == LEVEL_CITY) {
selectedCity = cityList.get(position);
queryCounties();
} else if (currentLevel == LEVEL_COUNTY) {
String weatherId = countyList.get(position).getWeatherId();
if (getActivity() instanceof MainActivity) {
Intent intent = new Intent(getActivity(), WeatherActivity.class);
intent.putExtra("weather_id",weatherId);
startActivity(intent);
getActivity().finish();
} else if (getActivity() instanceof WeatherActivity) {
WeatherActivity activity = (WeatherActivity) getActivity();
activity.drawerLayout.closeDrawers();
activity.swipeRefreshLayout.setRefreshing(true);
activity.requestWeather(weatherId);
} else if (getActivity() instanceof WeatherChooseAreaActivity) {
Intent intent = new Intent(getActivity(), WeatherActivity.class);
intent.putExtra("weather_choose_id",weatherId);
startActivity(intent);
getActivity().finish();
}
}
}
});
backButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (currentLevel == LEVEL_COUNTY) {
queryCity();
} else if (currentLevel == LEVEL_CITY) {
queryProvince();
}
}
});
}
//查询选中省的数据,优先从数据库查询,如果没有查询到再从数据库上查询
private void queryProvince() {
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 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 county : countyList) {
dataList.add(county.getCountyName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
currentLevel = LEVEL_COUNTY;
} else {
int provinceCode = selectedProvice.getProvinceCode();
int cityCode = selectedCity.getCityCode();
String address = "http://guolin.tech/api/china/" + provinceCode + "/" + cityCode;
queryFromServer(address, "county");
}
}
// 查询选中省内所有的市,优先从数据库查询,如果没有查询到再从数据库上查询
private void queryCity() {
titleText.setText(selectedProvice.getProvinceName());
backButton.setVisibility(View.VISIBLE);
cityList = DataSupport.where("provinceid = ?", String.valueOf(selectedProvice.getId())).find(City.class);
if (cityList.size() > 0) {
dataList.clear();
for (City city : cityList) {
dataList.add(city.getCityName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
currentLevel = LEVEL_CITY;
} else {
int provinceCode = selectedProvice.getProvinceCode();
String address = "http://guolin.tech/api/china/" + provinceCode;
queryFromServer(address, "city");
}
}
/**
* 根据传入的地址和类型从服务器上查询市县数据
* @param address
* @param type
*/
private void queryFromServer(String address, final String type) {
showProgressDialog();
HttpUtil.sendOkHttpRequest(address, new Callback() {
// 通过runOnUiThread()方法回到主线程处理逻辑
@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 json = response.body().string();
boolean result = false;
if ("province".equals(type)) {
result = Util.handleProvinceResponce(json);
} else if ("city".equals(type)) {
result = Util.handleCityResponse(json, selectedProvice.getId());
} else if ("county".equals(type)) {
result = Util.handleCountyResponse(json, selectedCity.getId());
}
if (result) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
closeProgressDialog();
if ("province".equals(type)) {
queryProvince();
}else if ("city".equals(type)) {
queryCity();
}else if ("county".equals(type)) {
queryCounties();
}
}
});
}
}
});
}
/**
* 显示对话框
*/
private void showProgressDialog() {
if (progressDialog == null) {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("数据加载中...");
progressDialog.setCanceledOnTouchOutside(false);
}
progressDialog.show();
}
/**
* 关闭对话框
*/
private void closeProgressDialog(){
if (progressDialog != null) {
progressDialog.dismiss();
}
}
}
- 显示天气的Activity,WeatherActivity.java
public class WeatherActivity extends AppCompatActivity {
private List
public class Util {
//解析和处理服务器返回的省级数据
public static boolean handleProvinceResponce(String response) {
if (!TextUtils.isEmpty(response)) {
try {
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"));
//保存数据到数据表
province.save();
}
return true;
} catch (JSONException e) {
e.printStackTrace();
}
}
return false;
}
//解析和处理服务器返回的市级数据
public static boolean handleCityResponse(String reponse, int province){
if (!TextUtils.isEmpty(reponse)) {
try {
JSONArray jsonArray = new JSONArray(reponse);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
City city = new City();
city.setCityName(jsonObject.getString("name"));
city.setCityCode(jsonObject.getInt("id"));
city.setProvinceId(province);
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;
}
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 (JSONException e) {
e.printStackTrace();
}
return null;
}
}