package com.example.administrator.coolweather;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.administrator.coolweather.db.City;
import com.example.administrator.coolweather.db.County;
import com.example.administrator.coolweather.db.Province;
import com.example.administrator.coolweather.util.HttpUtil;
import com.example.administrator.coolweather.util.Utility;
import org.litepal.crud.DataSupport;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
/**
* Created by Administrator on 2018/4/24.
*/
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;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,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<>(getContext(),android.R.layout.simple_list_item_1,dataList);
listView.setAdapter(adapter);
return view;
}
@Override
public void onActivityCreated(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();
}
}
});
backButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
if(currentLevel==LEVEL_COUNTY){
queryCities();
}else if(currentLevel==LEVEL_CITY){
queryProvinces();
}
}
});
queryProvinces();
}
/*
查詢全國所有的省,先從資料庫查詢,如果沒有查詢到再去服務器上查詢
放到ListView中
*/
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()+" "+province.getProvinceCode()+" "+province.getId());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
currentLevel=LEVEL_PROVINCE;
}else{
String address="http://guolin.tech/api/china";
queryFromServer(address,"province");
}
}
/*
查詢選中省內所有的市,優先從資料庫查詢,如果沒有查詢到再到服務器上查詢
放到ListView中
*/
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 city:cityList){
dataList.add(city.getCityName()+" "+city.getCityCode()+" "+city.getProvinceId());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
currentLevel=LEVEL_CITY;
}else{
int provinceCode=selectedProvince.getProvinceCode();
String address="http://guolin.tech/api/china/"+provinceCode;
queryFromServer(address,"city");
}
}
/*
查詢市內所有的縣,優先從資料庫查詢,如果沒有查詢到再去服務器上查詢
放到ListView中
*/
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=selectedProvince.getProvinceCode();
int cityCode=selectedCity.getCityCode();
String address="http://guolin.tech/api/china/"+provinceCode+"/"+cityCode;
queryFromServer(address,"county");
}
}
/*
根據傳入的地址和型別從服務器上查詢資料
*/
private void queryFromServer(String address,final String type){
showProgressDialog();
HttpUtil.sendOkHttpRequest(address,new Callback(){
@Override
public void onResponse(Call call,Response response)throws IOException{
String responseText=response.body().toString();
boolean result=false;
//如果配對,把從服務器查詢到的JSON資料配對到資料庫中
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();
//從資料庫中查詢所有的省,放到ListView中
if("province".equals(type)){
queryProvinces();
}else if("city".equals(type)){
queryCities();
}else if("county".equals(type)){
queryCounties();
}
}
});
}
}
@Override
public void onFailure(Call call,IOException e){
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
closeProgressDialog();
Toast.makeText(getContext(),"加載失敗",Toast.LENGTH_SHORT).show();
}
});
}
});
}
/*
顯示進度對話框
*/
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();
}
}
}
uj5u.com熱心網友回復:
package com.example.administrator.coolweather.util;
import android.text.TextUtils;
import com.example.administrator.coolweather.db.City;
import com.example.administrator.coolweather.db.County;
import com.example.administrator.coolweather.db.Province;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by Administrator on 2018/4/24.
*/
public class Utility {
/**
* 決議和處理服務器回傳的省級資料
*/
public static boolean handleProvinceResponse(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 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;
}
}
package com.example.administrator.coolweather.util;
import okhttp3.OkHttpClient;
import okhttp3.Request;
/**
* Created by Administrator on 2018/4/24.
*/
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);
}
}
uj5u.com熱心網友回復:
運行后就會出現一直加載的狀態
uj5u.com熱心網友回復:
有大佬幫忙嗎?陷在這里了。。。uj5u.com熱心網友回復:
你這個是不是沒有給網路權限啊,自己再檢查一下。還有就是郭霖大神不是在https://github.com/guolindev/booksource提供了原始碼么,你可以下載參考下,下載下來的chapter14這個檔案夾就是你這個專案
uj5u.com熱心網友回復:
我也是死在這上面,請問是怎么解決這個一直正在加載的問題,加急啊!!!!麻煩看到及時回復,現在已經死了差不多一個星期出不來了uj5u.com熱心網友回復:
所有你是不知道怎么解決咯轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/109875.html
標籤:Android
