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>
Android 遍历全国地区位置(一)的更多相关文章
- Android 遍历全国的地区二(获取天气)
根据上次的内容 1. 界面布局 weather_layout.xml <LinearLayout xmlns:android="http://schemas.android.com/a ...
- 【百度地图API】建立全国银行位置查询系统(四)——如何利用百度地图的数据生成自己的标注
原文:[百度地图API]建立全国银行位置查询系统(四)--如何利用百度地图的数据生成自己的标注 摘要: 上一章留个悬念,"如果自己没有地理坐标的数据库,应该怎样制作银行的分布地图呢?&quo ...
- Android View各种尺寸位置相关的方法探究
Android View各种尺寸位置相关的方法探究 本来想做一个View间的碰撞检测之类的. 动手做了才发现不是想象的那么简单. 首先,写好了碰撞检测的工具类如下: package com.mengd ...
- android EditText获取光标位置并安插字符删除字符
android EditText获取光标位置并插入字符删除字符1.获取光标位置int index = editText.getSelectionStart(); 2.在光标处插入字符int index ...
- 【百度地图API】建立全国银行位置查询系统(五)——如何更改百度地图的信息窗口内容?
原文:[百度地图API]建立全国银行位置查询系统(五)--如何更改百度地图的信息窗口内容? 摘要: 酷讯.搜房.去哪儿网等大型房产.旅游酒店网站,用的是百度的数据库,却显示了自定义的信息窗口内容,这是 ...
- 【百度地图API】建立全国银行位置查询系统(三)——如何在地图上添加银行标注
原文:[百度地图API]建立全国银行位置查询系统(三)--如何在地图上添加银行标注 <摘要>你将在第三章中学会以下知识: 如何在地图上添加带银行logo的标注?(你也可以换成商场logo, ...
- 【百度地图API】建立全国银行位置查询系统(二)——怎样为地图添加控件
原文:[百度地图API]建立全国银行位置查询系统(二)--怎样为地图添加控件 <摘要>你将在第二章中学会以下知识: 使用手写代码的利器——notepad++: 如何为地图添加控件——鱼骨. ...
- 【百度地图API】建立全国银行位置查询系统(一)——如何创建地图
原文:[百度地图API]建立全国银行位置查询系统(一)--如何创建地图 <摘要>你将在第一章中学会以下知识: 如何创建一个网页文件 怎样利用百度地图API建立一张2D地图,以及3D地图 如 ...
- Android 设置EditText光标位置(转)
Android 设置EditText光标位置 最后 CharSequence text = edtTxt_my_account_edit_nickname.getText();if (text ins ...
随机推荐
- 自动化工具构建vue项目
其实之前对vue的话也有过一段时间的学习,博客园也是写了5篇vue的学习笔记.但是一直是通过CDN的方式在html文件头部引入vue.js,然后实例化vue对象绑定Dom,写组件写方法.就算是在实际项 ...
- Python开发【面试】:刷题
面试题 1.到底什么是Python? Python是一种解释型语言.这就是说,与C语言和C的衍生语言不同,Python代码在运行之前不需要编译(一边编写一边执行,先把代码转化成字节码,然后python ...
- 双态运维联盟(BOA)正式成立
3月1日,由联想.新华三.华为等12家IT企业在北京正式达成协议,联合发起成立“双态运维联盟”.中国电子工业标准技术协会.信息技术服务分会数据中心运营管理工作组(DCMG)组长肖建一先生出席了会议. ...
- ROS,launch学习
想象一下,如果一个ros工程里包含几十个节点,我们在命令行窗口一个个的开启它们,是一件多么耗时间,多么没有意义的浪费. launch功能可以解决这一问题,启动launch文件时ROS中非常重要的,有用 ...
- OpenCV Windows7 VC6.0安装以及HelloWorld
anna在实验室配置OpenCV的时候,按照中文网站的介绍,很顺利的就完成了.可是回到家情况就大不一样!!总是在链接的时候报错,不是少这个lib就是少那个lib大哭最后查明是anna马虎,忘了将C:\ ...
- R语言编程
R中的帮助文档非常有用,其中有四种类型的帮助 help(functionname) 对已经加载包所含的函数显示其帮助文档,用?号也是一样的. help.search('keyword') 对已经安装的 ...
- Python Web开发之路
Flask相关 1.DBUtils数据库连接池 2.Flask之初体验 3.Flask之WTForms 4.Flask之信号 5.Flask之flask-session 6.Flask之flask-s ...
- STM32端口输入输出模式配置
STM32的IO口模式配置 根据数据手册提供的信息,stm32的io口一共有八种模式,他们分别是: 四种输入模式 上拉输入:通过内部的上拉电阻将一个不确定的信号通过一个电阻拉到高电平. 下拉输入:把电 ...
- Python学习札记(三十七) 面向对象编程 Object Oriented Program 8 @property
参考:@property NOTE 1.在绑定参数时,为了避免对属性不符合逻辑的操作,需要对传入的参数进行审核. #!/usr/bin/env python3 class MyClass(object ...
- UVa 10534 波浪子序列(快速求LIS)
https://vjudge.net/problem/UVA-10534 题意:给定一个长度为n的整数序列,求一个最长子序列(不一定连续),使得该序列的长度为2k+1,前k+1个数严格递增,后k+1个 ...