Android 遍历全国地区位置(一)

时间:2023-03-09 07:51:29
Android 遍历全国地区位置(一)

Android 遍历全国地区位置(一)Android 遍历全国地区位置(一)Android 遍历全国地区位置(一)

1.布局

choose_area.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"> <RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#484E61"> <TextView
android:id="@+id/title_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textColor="#fff"
android:textSize="24sp" />
</RelativeLayout> <ListView
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"> </ListView>
</LinearLayout>

2. 本地数据

2.1 省

Province.java
public class Province {
private int id;
private String provinceName;
private String 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 String getProvinceCode() {
return provinceCode;
} public void setProvinceCode(String provinceCode) {
this.provinceCode = provinceCode;
} }

2.2 市

City.java

public class City {
private int id;
private String cityName;
private String cityCode;
private int provinceId; public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getCityCode() {
return cityCode;
} public void setCityCode(String cityCode) {
this.cityCode = cityCode;
} public String getCityName() {
return cityName;
} public void setCityName(String cityName) {
this.cityName = cityName;
} public int getProvinceId() {
return provinceId;
} public void setProvinceId(int provinceId) {
this.provinceId = provinceId;
}
}

2.3 县

county.java

public class County {
private int id;
private String countyName;
private String countyCode;
private int cityId; public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getCountyName() {
return countyName;
} public void setCountyName(String countyName) {
this.countyName = countyName;
} public String getCountyCode() {
return countyCode;
} public void setCountyCode(String countyCode) {
this.countyCode = countyCode;
} public int getCityId() {
return cityId;
} public void setCityId(int cityId) {
this.cityId = cityId;
}
}

2.4  创建本地数据库

CoolWeatherOpenHelper.java

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper; public class CoolWeatherOpenHelper extends SQLiteOpenHelper {
//注意 点后面要一个空格!
public static final String CREATE_PROVINCE = "create table Province ("
+ "id integer primary key autoincrement, "
+ "province_name text, "
+ "province_code text)";
public static final String CREATE_CITY = "create table City ("
+ "id integer primary key autoincrement, "
+ "city_name text, "
+ "city_code text, "
+ "province_id integer)";
public static final String CREATE_COUNTY = "create table County ("
+ "id integer primary key autoincrement, "
+ "county_name text, "
+ "county_code text, "
+ "city_id integer)";
//注意手动打包 CursorFactory类,不可以自动在前面加上,就会出错.
public CoolWeatherOpenHelper(Context context, String name, CursorFactory factory,int version) {
super(context, name, factory, version);
} @Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_PROVINCE);
db.execSQL(CREATE_CITY);
db.execSQL(CREATE_COUNTY); } @Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { }
}

2.5 实例与数据库关联(实例的数据存储到本地数据库,从本地数据库中读取实例数据)

CoolWeatherDB.java

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase; import com.liqingweather.app.db.CoolWeatherOpenHelper; import java.util.ArrayList;
import java.util.List; /**
* Created by zps on 2015/9/12.
*/
public class CoolWeatherDB {
public static final int VERSION = 1;
public static final String DB_NAME = "cool_weather";
private static CoolWeatherDB coolWeatherDB;
private SQLiteDatabase db;
//单例模式
private CoolWeatherDB(Context context) {
CoolWeatherOpenHelper dbHelper = new CoolWeatherOpenHelper(context,
DB_NAME, null, VERSION);
db = dbHelper.getWritableDatabase();
} //synchronized 避免同步创建实例
public synchronized static CoolWeatherDB getInstance(Context context) {
if (coolWeatherDB == null) {
coolWeatherDB = new CoolWeatherDB(context);
}
return coolWeatherDB;
} public void saveProvince(Province province) {
if (province != null) {
/*ContentValues 和HashTable类似都是一种存储的机制 但是两者最大的区别就在于,
contenvalues只能存储基本类型的数据,像string,int之类的,
不能存储对象这种东西,而HashTable却可以存储对象。*/
ContentValues values = new ContentValues();
values.put("province_name", province.getProvinceName());
values.put("province_code", province.getProvinceCode());
db.insert("Province", null, values);
}
} public List<Province> loadProvinces() {
List<Province> list = new ArrayList<>();
/* Android的query函数:
String table = "Orders" ;
String[] columns = new String[] { "CustomerName" , "SUM(OrderPrice)" };
String selection = "Country=?" ;
String[] selectionArgs = new String[]{ "China" };
String groupBy = "CustomerName" ;
String having = "SUM(OrderPrice)>500" ;
String orderBy = "CustomerName" ;
Cursor c = db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy, null );*/
Cursor cursor = db.query("Province", null, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
Province province = new Province();
province.setId(cursor.getInt(cursor.getColumnIndex("id")));
province.setProvinceName(cursor.getString(cursor.getColumnIndex("province_name")));
province.setProvinceCode(cursor.getString(cursor.getColumnIndex("province_code")));
list.add(province);
} while (cursor.moveToNext());
}
if (cursor != null) {
cursor.close();
}
return list;
} public void saveCity(City city) {
if (city != null) {
ContentValues values = new ContentValues();
values.put("city_name", city.getCityName());
values.put("city_code", city.getCityCode());
values.put("province_id", city.getProvinceId());
db.insert("City", null, values);
}
} public List<City> loadCities(int provinceId) {
List<City> list = new ArrayList<>();
Cursor cursor = db.query("City", null, "province_id=?",
new String[]{String.valueOf(provinceId)}, null, null, null);
if (cursor.moveToFirst()) {
do {
City city = new City();
city.setId(cursor.getInt(cursor.getColumnIndex("id")));
city.setCityName(cursor.getString(cursor.getColumnIndex("city_name")));
city.setCityCode(cursor.getString(cursor.getColumnIndex("city_code")));
city.setProvinceId(provinceId);
list.add(city); } while (cursor.moveToNext());
}
if (cursor != null) {
cursor.close();
}
return list;
} public void saveCounty(County county) {
if (county != null) {
ContentValues values = new ContentValues();
values.put("county_name", county.getCountyName());
values.put("county_code", county.getCountyCode());
values.put("city_id", county.getCityId());
db.insert("County", null, values);
}
} public List<County> loadCounties(int cityId) {
List<County> list = new ArrayList<>();
Cursor cursor = db.query("County", null, "city_id = ?",
new String[]{String.valueOf(cityId)}, null, null, null);
if (cursor.moveToFirst()) {
do {
County county = new County();
county.setId(cursor.getInt(cursor.getColumnIndex("id")));
county.setCountyName(cursor.getString(cursor.getColumnIndex("county_name")));
county.setCountyCode(cursor.getString(cursor.getColumnIndex("county_code")));
county.setCityId(cityId);
list.add(county); } while (cursor.moveToNext());
}
if (cursor != null) {
cursor.close();
}
return list;
} }

3. 服务器

3.1 获取服务器的数据

HttpUtil.java

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL; /**
* Created by zps on 2015/9/12.
*/
public class HttpUtil {
public static void sendHttpRequest(final String address
, final HttpCallbackListener listener) {
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
try {
URL url = new URL(address);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000); InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
if (listener != null) {
listener.onFinish(response.toString());
}
} catch (Exception e) {
if (listener != null) {
listener.onError(e);
}
} finally {
if (connection != null) {
connection.disconnect(); }
}
}
}).start();
} }

3.2 HttpCallbackListener接口服务返回的结果

HttpCallbackListener.java

/**
* Created by zps on 2015/9/12.
*/
public interface HttpCallbackListener {
void onFinish(String response); void onError(Exception e);
}

3.3 服务器的数据解析

Utility.java

import android.text.TextUtils;
import com.liqingweather.app.model.City;
import com.liqingweather.app.model.CoolWeatherDB;
import com.liqingweather.app.model.County;
import com.liqingweather.app.model.Province; /**
* Created by zps on 2015/9/12.
*/
public class Utility { public synchronized static boolean handleProvincesResponse(CoolWeatherDB coolWeatherDB,String response){
//isEmpty用于判断""或null
if(!TextUtils.isEmpty(response)){
String[] allProvinces = response.split(",");
if (allProvinces != null && allProvinces.length>0){
for (String p : allProvinces){
//split分离,'\\|'传给正则就是"\|",表示对|进行转义,不作为特殊字符使用
String[] array = p.split("\\|");
Province province = new Province();
//数据格式为"代号|城市",故array[0]为代号
province.setProvinceCode(array[0]);
province.setProvinceName(array[1]);
coolWeatherDB.saveProvince(province);
}
return true;
} } return false;
}
public static boolean handleCitiesResponse(CoolWeatherDB coolWeatherDB,
String response, int provinceId) {
if (!TextUtils.isEmpty(response)) {
String[] allCities = response.split(",");
if (allCities != null && allCities.length > 0) {
for (String c : allCities) {
String[] array = c.split("\\|");
City city = new City();
city.setCityCode(array[0]);
city.setCityName(array[1]);
city.setProvinceId(provinceId);
coolWeatherDB.saveCity(city);
}
return true;
}
}
return false;
}
public static boolean handleCountiesResponse(CoolWeatherDB coolWeatherDB,
String response, int cityId) {
if (!TextUtils.isEmpty(response)) {
String[] allCounties = response.split(",");
if (allCounties != null && allCounties.length > 0) {
for (String c : allCounties) {
String[] array = c.split("\\|");
County county = new County();
county.setCountyCode(array[0]);
county.setCountyName(array[1]);
county.setCityId(cityId);
coolWeatherDB.saveCounty(county);
}
return true;
}
}
return false;
}
}

4. 遍历数据的活动

ChooseAreaActivity.java

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast; import com.liqingweather.app.R;
import com.liqingweather.app.model.City;
import com.liqingweather.app.model.CoolWeatherDB;
import com.liqingweather.app.model.County;
import com.liqingweather.app.model.Province;
import com.liqingweather.app.util.HttpCallbackListener;
import com.liqingweather.app.util.HttpUtil;
import com.liqingweather.app.util.Utility; import java.util.ArrayList;
import java.util.List; public class ChooseAreaActivity extends Activity {
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 ListView listView;
private ArrayAdapter<String> adapter;
private CoolWeatherDB coolWeatherDB;
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
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.choose_area);
titleText = (TextView) findViewById(R.id.title_text);
listView = (ListView) findViewById(R.id.list_view);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dataList);
listView.setAdapter(adapter);
coolWeatherDB = CoolWeatherDB.getInstance(this);
//注意AdapterView.OnItemClickListener()写法是错误的!个人理解,没有事先加载AdapterView.OnItemClickListener()方法
listView.setOnItemClickListener(new 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();
} }
});
queryProvinces();
} private void queryProvinces() {
provinceList = coolWeatherDB.loadProvinces();
if (provinceList.size() > 0) {
dataList.clear();
for (Province province : provinceList) {
dataList.add(province.getProvinceName());
}
//notifyDataSetChanged()可以在修改适配器绑定的数组后,
// 不用重新刷新Activity,通知Activity更新ListView。
adapter.notifyDataSetChanged();
listView.setSelection(0);
titleText.setText("中国");
currentLevel = LEVEL_PROVINCE;
} else {
//注意大小写"province"
queryFromServer(null, "province");
}
} private void queryCities() {
cityList = coolWeatherDB.loadCities(selectedProvince.getId());
if (cityList.size() > 0) {
dataList.clear();
for (City city : cityList) {
dataList.add(city.getCityName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
titleText.setText(selectedProvince.getProvinceName());
currentLevel = LEVEL_CITY;
} else { //注意是getProvinceCode()
queryFromServer(selectedProvince.getProvinceCode(), "city");
}
} private void queryCounties() {
countyList = coolWeatherDB.loadCounties(selectedCity.getId());
if (countyList.size() > 0) {
dataList.clear();
for (County county : countyList) {
dataList.add(county.getCountyName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
titleText.setText(selectedCity.getCityName());
currentLevel = LEVEL_COUNTY;
} else {
queryFromServer(selectedCity.getCityCode(), "county");
}
} private void queryFromServer(final String code, final String type) {
String address;
if (!TextUtils.isEmpty(code)) {
address = "http://www.weather.com.cn/data/list3/city" + code +
".xml";
} else {
address = "http://www.weather.com.cn/data/list3/city.xml";
}
showProgressDialog();
HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {
@Override
public void onFinish(String response) {
boolean result = false;
if ("province".equals(type)) {
result = Utility.handleProvincesResponse(coolWeatherDB,
response);
} else if ("city".equals(type)) {
result = Utility.handleCitiesResponse(coolWeatherDB,
response, selectedProvince.getId());
} else if ("county".equals(type)) {
result = Utility.handleCountiesResponse(coolWeatherDB,
response, selectedCity.getId());
}
if (result) { 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();
}
}
});
}
} @Override
public void onError(Exception e) { runOnUiThread(new Runnable() {
@Override
public void run() {
closeProgressDialog();
Toast.makeText(ChooseAreaActivity.this, "加载失败", Toast.LENGTH_SHORT).show();
}
});
}
});
} private void showProgressDialog() {
if (progressDialog == null) {
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("正在加载...");
progressDialog.setCanceledOnTouchOutside(false); }
progressDialog.show();
} private void closeProgressDialog() {
if (progressDialog != null) {
progressDialog.dismiss();
}
} @Override
public void onBackPressed() { if (currentLevel == LEVEL_COUNTY) {
queryCities(); } else if (currentLevel == LEVEL_CITY) {
queryProvinces();
} else {
finish();
}
}
}

5. AndroidManifest.xml

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

    <application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".activity.ChooseAreaActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity> </application> </manifest>

相关文章