码迷,mamicode.com
首页 > 其他好文 > 详细

1.选择城市

时间:2015-10-30 20:24:56      阅读:296      评论:0      收藏:0      [点我收藏+]

标签:

项目介绍
应用截图
技术分享技术分享
技术分享


主要功能
  • 写的一个APP总结一下
  • 使用车联网api解析天气数据并展示在界面
  • 定位
  • 通知栏
  • 桌面小部件
  • 动态添加删除城市并显示在界面上方便查看
选择城市界面
  • 首先我网上找了个城市json数据信息,然后自己做了个json数据存放在res的raw目录下
  • 然后需要解析出来存放在数据库中,不用每次都去解析json
CoolWeatherOpenHelper 
  1. public class CoolWeatherOpenHelper extends SQLiteOpenHelper {
  2. /**
  3. * Province表建表语句
  4. */
  5. public static final String CREATE_PROVINCE = "create table Province ("
  6. + "id integer primary key autoincrement, " + "province_name text)";
  7. /**
  8. * City表建表语句
  9. */
  10. public static final String CREATE_CITY = "create table City ("
  11. + "id integer primary key autoincrement, " + "city_name text, "
  12. + "city_code text, " + "province_id integer)";
  13. /**
  14. * 创建选中城市的表
  15. */
  16. public static final String CREATE_ADDCITY = "create table AddCity("
  17. + "id integer primary key autoincrement,"
  18. + " city_name char(10) UNIQUE )";
  19. public CoolWeatherOpenHelper(Context context, String name,
  20. CursorFactory factory, int version) {
  21. super(context, name, factory, version);
  22. }
  23. @Override
  24. public void onCreate(SQLiteDatabase db) {
  25. db.execSQL(CREATE_PROVINCE); // 创建Province表
  26. db.execSQL(CREATE_CITY); // 创建City表
  27. db.execSQL(CREATE_ADDCITY);// 创建选中城市表
  28. }
  29. @Override
  30. public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  31. }
  32. }
CoolWeatherDB 
  1. public class CoolWeatherDB {
  2. /**
  3. * 数据库名
  4. */
  5. public static final String DB_NAME = "cool_weather";
  6. /**
  7. * 数据库版本
  8. */
  9. public static final int VERSION = 1;
  10. private static CoolWeatherDB coolWeatherDB;
  11. private SQLiteDatabase db;
  12. private String cityName;
  13. /**
  14. * 将构造方法私有化
  15. */
  16. private CoolWeatherDB(Context context) {
  17. CoolWeatherOpenHelper dbHelper = new CoolWeatherOpenHelper(context,
  18. DB_NAME, null, VERSION);
  19. db = dbHelper.getWritableDatabase();
  20. }
  21. /**
  22. * 获取CoolWeatherDB的实例。
  23. */
  24. public synchronized static CoolWeatherDB getInstance(Context context) {
  25. if (coolWeatherDB == null) {
  26. coolWeatherDB = new CoolWeatherDB(context);
  27. }
  28. return coolWeatherDB;
  29. }
  30. /**
  31. * 选中的城市添加到数据库
  32. */
  33. public void saveAddCity(AddCity addCity) {
  34. if (addCity != null) {
  35. ContentValues values = new ContentValues();
  36. try {
  37. values.put("city_name", addCity.getCityName());
  38. db.insert("AddCity", null, values);
  39. } catch (Exception e) {
  40. e.printStackTrace();
  41. }
  42. }
  43. }
  44. /**
  45. * 读取保存的城市
  46. */
  47. public List<AddCity> loadAddCity() {
  48. List<AddCity> list = new ArrayList<AddCity>();
  49. Cursor cursor = db.query("AddCity", null, null, null, null, null, null);
  50. if (cursor.moveToFirst()) {
  51. do {
  52. AddCity addCity = new AddCity();
  53. addCity.setCityName(cursor.getString(cursor
  54. .getColumnIndex("city_name")));
  55. list.add(addCity);
  56. } while (cursor.moveToNext());
  57. }
  58. return list;
  59. }
  60. /**
  61. * 删除addcity表中的数据
  62. */
  63. public void removeCity(String name) {
  64. int i = db.delete("AddCity", " city_name=?", new String[] { name });
  65. System.out.println("i--" + i);
  66. }
  67. /**
  68. * 将Province实例存储到数据库。
  69. */
  70. public void saveProvince(Province province) {
  71. if (province != null) {
  72. ContentValues values = new ContentValues();
  73. values.put("province_name", province.getProvinceName());
  74. db.insert("Province", null, values);
  75. }
  76. }
  77. /**
  78. * 从数据库读取全国所有的省份信息。
  79. */
  80. public List<Province> loadProvinces() {
  81. List<Province> list = new ArrayList<Province>();
  82. Cursor cursor = db
  83. .query("Province", null, null, null, null, null, null);
  84. if (cursor.moveToFirst()) {
  85. do {
  86. Province province = new Province();
  87. province.setId(cursor.getInt(cursor.getColumnIndex("id")));
  88. province.setProvinceName(cursor.getString(cursor
  89. .getColumnIndex("province_name")));
  90. list.add(province);
  91. } while (cursor.moveToNext());
  92. }
  93. return list;
  94. }
  95. /**
  96. * 将City实例存储到数据库。
  97. */
  98. public void saveCity(City city) {
  99. if (city != null) {
  100. ContentValues values = new ContentValues();
  101. values.put("city_name", city.getCityName());
  102. values.put("city_code", city.getCityCode());
  103. values.put("province_id", city.getProvinceId());
  104. db.insert("City", null, values);
  105. }
  106. }
  107. /**
  108. * 从数据库读取某省下所有的城市信息。
  109. */
  110. public List<City> loadCities(int provinceId) {
  111. List<City> list = new ArrayList<City>();
  112. Cursor cursor = db.query("City", null, "province_id = ?",
  113. new String[] { String.valueOf(provinceId) }, null, null, null);
  114. if (cursor.moveToFirst()) {
  115. do {
  116. City city = new City();
  117. city.setId(cursor.getInt(cursor.getColumnIndex("id")));
  118. city.setCityName(cursor.getString(cursor
  119. .getColumnIndex("city_name")));
  120. city.setCityCode(cursor.getString(cursor
  121. .getColumnIndex("city_code")));
  122. city.setProvinceId(provinceId);
  123. list.add(city);
  124. } while (cursor.moveToNext());
  125. }
  126. return list;
  127. }
  128. }
创建工具类去解析json数据
  1. public class Utility {
  2. public static void json(Context context, CoolWeatherDB coolWeatherDB) {
  3. try {
  4. // 读取 json文件
  5. InputStream is = context.getResources().openRawResource(
  6. R.raw.cityinfo);
  7. BufferedReader reader = new BufferedReader(
  8. new InputStreamReader(is));
  9. StringBuilder response = new StringBuilder();
  10. String line;
  11. while ((line = reader.readLine()) != null) {
  12. response.append(line);
  13. }
  14. String json = response.toString();
  15. // 将字符串json转换为json对象,以便于取出数据
  16. JSONObject jsonObject = new JSONObject(json);
  17. // 解析info数组,解析中括号括起来的内容就表示一个数组,使用JSONArray对象解析
  18. JSONArray provinceArray = jsonObject.getJSONArray("城市代码");
  19. // 遍历JSONArray数组
  20. for (int i = 0; i < provinceArray.length(); i++) {
  21. // 取出省对象
  22. JSONObject provinceObj = provinceArray.getJSONObject(i);
  23. // 获得省的名字
  24. String provinceName = provinceObj.getString("省");
  25. // 中括号括起来的内容就表示一个JSONArray,所以这里要再创建一个JSONArray对象
  26. JSONArray cityArray = provinceObj.getJSONArray("市");
  27. for (int j = 0; j < cityArray.length(); j++) {
  28. JSONObject cityObj = cityArray.getJSONObject(j);
  29. String cityName = cityObj.getString("市名");
  30. String cityCode = cityObj.getString("编码");
  31. City city = new City();
  32. city.setCityName(cityName);
  33. city.setCityCode(cityCode);
  34. city.setProvinceId(i);
  35. coolWeatherDB.saveCity(city);
  36. }
  37. Province province = new Province();
  38. province.setProvinceName(provinceName);
  39. // 将解析出来的数据存储到Province表
  40. coolWeatherDB.saveProvince(province);
  41. }
  42. } catch (Exception e) {
  43. e.printStackTrace();
  44. }
  45. }
  46. }
选择城市activity布局
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. android:layout_width="match_parent"
  3. android:layout_height="match_parent"
  4. android:orientation="vertical" >
  5. <RelativeLayout
  6. android:layout_width="match_parent"
  7. android:layout_height="50dp"
  8. android:background="#484E61" >
  9. <TextView
  10. android:id="@+id/title_text"
  11. android:layout_width="wrap_content"
  12. android:layout_height="wrap_content"
  13. android:layout_centerInParent="true"
  14. android:textColor="#fff"
  15. android:textSize="24sp" />
  16. </RelativeLayout>
  17. <ListView
  18. android:id="@+id/list_view"
  19. android:layout_width="match_parent"
  20. android:layout_height="match_parent" >
  21. </ListView>
  22. </LinearLayout>
选择城市activity,软件一进来此activity 
 
  1. public class ChooseAreaActivity extends BaseActivity {
  2. public static final int LEVEL_PROVINCE = 0;
  3. public static final int LEVEL_CITY = 1;
  4. private TextView titleText;
  5. private ListView listView;
  6. private ArrayAdapter<String> adapter;
  7. private CoolWeatherDB coolWeatherDB;
  8. private List<String> dataList = new ArrayList<String>();// 存放城市
  9. private SharedPreferences prefs;
  10. private AddCity addCity;// 添加的城市
  11. /**
  12. * 省列表
  13. */
  14. private List<Province> provinceList;
  15. /**
  16. * 市列表
  17. */
  18. private List<City> cityList;
  19. /**
  20. * 选中的省份
  21. */
  22. private Province selectedProvince;
  23. /**
  24. * 当前选中的级别
  25. */
  26. private int currentLevel;
  27. /**
  28. * 是否从CityActivity中跳转过来。
  29. */
  30. private boolean isFromCityActivity;
  31. @Override
  32. protected void onCreate(Bundle savedInstanceState) {
  33. super.onCreate(savedInstanceState);
  34. isFromCityActivity = getIntent().getBooleanExtra("from_city_activity",
  35. false);
  36. prefs = PreferenceManager.getDefaultSharedPreferences(this);
  37. // 已经选择了城市且不是从CityActivity跳转过来,才会直接跳转到WeatherActivity,否则会一进来就又调到WeatherActivity
  38. if (prefs.getBoolean("city_selected", false) && !isFromCityActivity) {
  39. Intent intent = new Intent(this, WeatherActivity.class);
  40. startActivity(intent);
  41. finish();
  42. return;
  43. }
  44. requestWindowFeature(Window.FEATURE_NO_TITLE);
  45. setContentView(R.layout.choose_activity);
  46. listView = (ListView) findViewById(R.id.list_view);
  47. titleText = (TextView) findViewById(R.id.title_text);
  48. coolWeatherDB = CoolWeatherDB.getInstance(this);
  49. addCity = new AddCity();
  50. adapter = new ArrayAdapter<String>(this,
  51. android.R.layout.simple_list_item_1, dataList);
  52. listView.setAdapter(adapter);
  53. listView.setOnItemClickListener(new OnItemClickListener() {
  54. @Override
  55. public void onItemClick(AdapterView<?> parent, View view,
  56. int position, long id) {
  57. if (currentLevel == LEVEL_PROVINCE) {
  58. selectedProvince = provinceList.get(position);// 点0-北京-查询城市
  59. queryCities();
  60. } else if (currentLevel == LEVEL_CITY) {
  61. String cityName = cityList.get(position).getCityName();
  62. Intent intent = new Intent(ChooseAreaActivity.this,
  63. WeatherActivity.class);// 选择的城市名传递到WeatherActivity
  64. intent.putExtra("cityName", cityName);
  65. addCity.setCityName(cityName);
  66. coolWeatherDB.saveAddCity(addCity);// 保存到数据库
  67. System.out.println("ChooseAreaActivity" + cityName);
  68. startActivity(intent);
  69. finish();
  70. }
  71. }
  72. });
  73. queryProvinces(); // 默认加载省级数据
  74. }
  75. /**
  76. * 从数据库查询查询全国所有的省
  77. */
  78. private void queryProvinces() {
  79. provinceList = coolWeatherDB.loadProvinces();
  80. if (provinceList.size() > 0) {
  81. dataList.clear();// notifyDataSetChanged前先clear
  82. for (Province province : provinceList) {
  83. dataList.add(province.getProvinceName());
  84. }
  85. adapter.notifyDataSetChanged();
  86. listView.setSelection(0);
  87. titleText.setText("中国");
  88. currentLevel = LEVEL_PROVINCE;
  89. } else {
  90. Utility.json(this, coolWeatherDB);// 软件一进来先解析json(存放的城市信息)
  91. queryProvinces();
  92. }
  93. }
  94. /**
  95. * 从数据库查询选中省内所有的市
  96. */
  97. private void queryCities() {
  98. cityList = coolWeatherDB.loadCities(selectedProvince.getId() - 1);// 点0-北京-数据库里是1,所以-1
  99. if (cityList.size() > 0) {
  100. dataList.clear();
  101. for (City city : cityList) {
  102. dataList.add(city.getCityName());
  103. }
  104. adapter.notifyDataSetChanged();
  105. listView.setSelection(0);
  106. titleText.setText(selectedProvince.getProvinceName());
  107. currentLevel = LEVEL_CITY;
  108. } else {
  109. Utility.json(this, coolWeatherDB);
  110. queryCities();// 第一次进来开始解析json数据,插入数据库。第二进来直接从数据库获取
  111. }
  112. }
  113. /**
  114. * 捕获Back按键,根据当前的级别来判断,此时应该返回市列表、省列表、还是直接退出。
  115. */
  116. @Override
  117. public void onBackPressed() {
  118. if (currentLevel == LEVEL_CITY) {
  119. queryProvinces();
  120. } else {
  121. finish();
  122. }
  123. }
  124. }





1.选择城市

标签:

原文地址:http://www.cnblogs.com/liuyu0529/p/4924252.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!