标签:
项目介绍
public class CoolWeatherOpenHelper extends SQLiteOpenHelper {
/**
* Province表建表语句
*/
public static final String CREATE_PROVINCE = "create table Province ("
+ "id integer primary key autoincrement, " + "province_name text)";
/**
* City表建表语句
*/
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_ADDCITY = "create table AddCity("
+ "id integer primary key autoincrement,"
+ " city_name char(10) UNIQUE )";
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); // 创建Province表
db.execSQL(CREATE_CITY); // 创建City表
db.execSQL(CREATE_ADDCITY);// 创建选中城市表
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
public class CoolWeatherDB {
/**
* 数据库名
*/
public static final String DB_NAME = "cool_weather";
/**
* 数据库版本
*/
public static final int VERSION = 1;
private static CoolWeatherDB coolWeatherDB;
private SQLiteDatabase db;
private String cityName;
/**
* 将构造方法私有化
*/
private CoolWeatherDB(Context context) {
CoolWeatherOpenHelper dbHelper = new CoolWeatherOpenHelper(context,
DB_NAME, null, VERSION);
db = dbHelper.getWritableDatabase();
}
/**
* 获取CoolWeatherDB的实例。
*/
public synchronized static CoolWeatherDB getInstance(Context context) {
if (coolWeatherDB == null) {
coolWeatherDB = new CoolWeatherDB(context);
}
return coolWeatherDB;
}
/**
* 选中的城市添加到数据库
*/
public void saveAddCity(AddCity addCity) {
if (addCity != null) {
ContentValues values = new ContentValues();
try {
values.put("city_name", addCity.getCityName());
db.insert("AddCity", null, values);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 读取保存的城市
*/
public List<AddCity> loadAddCity() {
List<AddCity> list = new ArrayList<AddCity>();
Cursor cursor = db.query("AddCity", null, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
AddCity addCity = new AddCity();
addCity.setCityName(cursor.getString(cursor
.getColumnIndex("city_name")));
list.add(addCity);
} while (cursor.moveToNext());
}
return list;
}
/**
* 删除addcity表中的数据
*/
public void removeCity(String name) {
int i = db.delete("AddCity", " city_name=?", new String[] { name });
System.out.println("i--" + i);
}
/**
* 将Province实例存储到数据库。
*/
public void saveProvince(Province province) {
if (province != null) {
ContentValues values = new ContentValues();
values.put("province_name", province.getProvinceName());
db.insert("Province", null, values);
}
}
/**
* 从数据库读取全国所有的省份信息。
*/
public List<Province> loadProvinces() {
List<Province> list = new ArrayList<Province>();
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")));
list.add(province);
} while (cursor.moveToNext());
}
return list;
}
/**
* 将City实例存储到数据库。
*/
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<City>();
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());
}
return list;
}
}
public class Utility {
public static void json(Context context, CoolWeatherDB coolWeatherDB) {
try {
// 读取 json文件
InputStream is = context.getResources().openRawResource(
R.raw.cityinfo);
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
String json = response.toString();
// 将字符串json转换为json对象,以便于取出数据
JSONObject jsonObject = new JSONObject(json);
// 解析info数组,解析中括号括起来的内容就表示一个数组,使用JSONArray对象解析
JSONArray provinceArray = jsonObject.getJSONArray("城市代码");
// 遍历JSONArray数组
for (int i = 0; i < provinceArray.length(); i++) {
// 取出省对象
JSONObject provinceObj = provinceArray.getJSONObject(i);
// 获得省的名字
String provinceName = provinceObj.getString("省");
// 中括号括起来的内容就表示一个JSONArray,所以这里要再创建一个JSONArray对象
JSONArray cityArray = provinceObj.getJSONArray("市");
for (int j = 0; j < cityArray.length(); j++) {
JSONObject cityObj = cityArray.getJSONObject(j);
String cityName = cityObj.getString("市名");
String cityCode = cityObj.getString("编码");
City city = new City();
city.setCityName(cityName);
city.setCityCode(cityCode);
city.setProvinceId(i);
coolWeatherDB.saveCity(city);
}
Province province = new Province();
province.setProvinceName(provinceName);
// 将解析出来的数据存储到Province表
coolWeatherDB.saveProvince(province);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
<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>
public class ChooseAreaActivity extends BaseActivity {
public static final int LEVEL_PROVINCE = 0;
public static final int LEVEL_CITY = 1;
private TextView titleText;
private ListView listView;
private ArrayAdapter<String> adapter;
private CoolWeatherDB coolWeatherDB;
private List<String> dataList = new ArrayList<String>();// 存放城市
private SharedPreferences prefs;
private AddCity addCity;// 添加的城市
/**
* 省列表
*/
private List<Province> provinceList;
/**
* 市列表
*/
private List<City> cityList;
/**
* 选中的省份
*/
private Province selectedProvince;
/**
* 当前选中的级别
*/
private int currentLevel;
/**
* 是否从CityActivity中跳转过来。
*/
private boolean isFromCityActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
isFromCityActivity = getIntent().getBooleanExtra("from_city_activity",
false);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
// 已经选择了城市且不是从CityActivity跳转过来,才会直接跳转到WeatherActivity,否则会一进来就又调到WeatherActivity
if (prefs.getBoolean("city_selected", false) && !isFromCityActivity) {
Intent intent = new Intent(this, WeatherActivity.class);
startActivity(intent);
finish();
return;
}
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.choose_activity);
listView = (ListView) findViewById(R.id.list_view);
titleText = (TextView) findViewById(R.id.title_text);
coolWeatherDB = CoolWeatherDB.getInstance(this);
addCity = new AddCity();
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, dataList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (currentLevel == LEVEL_PROVINCE) {
selectedProvince = provinceList.get(position);// 点0-北京-查询城市
queryCities();
} else if (currentLevel == LEVEL_CITY) {
String cityName = cityList.get(position).getCityName();
Intent intent = new Intent(ChooseAreaActivity.this,
WeatherActivity.class);// 选择的城市名传递到WeatherActivity
intent.putExtra("cityName", cityName);
addCity.setCityName(cityName);
coolWeatherDB.saveAddCity(addCity);// 保存到数据库
System.out.println("ChooseAreaActivity" + cityName);
startActivity(intent);
finish();
}
}
});
queryProvinces(); // 默认加载省级数据
}
/**
* 从数据库查询查询全国所有的省
*/
private void queryProvinces() {
provinceList = coolWeatherDB.loadProvinces();
if (provinceList.size() > 0) {
dataList.clear();// notifyDataSetChanged前先clear
for (Province province : provinceList) {
dataList.add(province.getProvinceName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
titleText.setText("中国");
currentLevel = LEVEL_PROVINCE;
} else {
Utility.json(this, coolWeatherDB);// 软件一进来先解析json(存放的城市信息)
queryProvinces();
}
}
/**
* 从数据库查询选中省内所有的市
*/
private void queryCities() {
cityList = coolWeatherDB.loadCities(selectedProvince.getId() - 1);// 点0-北京-数据库里是1,所以-1
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 {
Utility.json(this, coolWeatherDB);
queryCities();// 第一次进来开始解析json数据,插入数据库。第二进来直接从数据库获取
}
}
/**
* 捕获Back按键,根据当前的级别来判断,此时应该返回市列表、省列表、还是直接退出。
*/
@Override
public void onBackPressed() {
if (currentLevel == LEVEL_CITY) {
queryProvinces();
} else {
finish();
}
}
}
标签:
原文地址:http://www.cnblogs.com/liuyu0529/p/4924252.html