Android 实现省份城市的选择,并获取城市编号

该程序主要使用 中央气象局 省份 城市数据库为基础 进行读取

城市数据库下载 http://download.csdn.net/download/xianqiang1/3896880 感谢该兄弟的分享

下载的数据库 db_weather.db 放到sdcard/weather 目录下面 方便后续操作

为了更好的了解数据库,使用 SQLite Database Browser 可以打开数据库 查看数据 和表等信息,如下

了解了表的构成可以实现操作了

androidManifest.xml

配置文件声明 添加操作sdcard 权限

[html]  view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3. package="com.cityselection"
  4. android:versionCode="1"
  5. android:versionName="1.0" >
  6. <uses-sdk android:minSdkVersion="8" />
  7. <!-- sdcard操作允许 -->
  8. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
  9. <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
  10. <application
  11. android:icon="@drawable/ic_launcher"
  12. android:label="@string/app_name" >
  13. <activity
  14. android:name=".City_SelectionActivity"
  15. android:label="@string/app_name" >
  16. <intent-filter>
  17. <action android:name="android.intent.action.MAIN" />
  18. <category android:name="android.intent.category.LAUNCHER" />
  19. </intent-filter>
  20. </activity>
  21. </application>
  22. </manifest>
[html]  view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.cityselection"  
  4.     android:versionCode="1"  
  5.     android:versionName="1.0" >  
  6.   
  7.     <uses-sdk android:minSdkVersion="8" />  
  8.     <!-- sdcard操作允许 -->  
  9.     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  
  10.     <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>  
  11.     <application  
  12.         android:icon="@drawable/ic_launcher"  
  13.         android:label="@string/app_name" >  
  14.         <activity  
  15.             android:name=".City_SelectionActivity"  
  16.             android:label="@string/app_name" >  
  17.             <intent-filter>  
  18.                 <action android:name="android.intent.action.MAIN" />  
  19.   
  20.                 <category android:name="android.intent.category.LAUNCHER" />  
  21.             </intent-filter>  
  22.         </activity>  
  23.     </application>  
  24.   
  25. </manifest>  


布局文件main.xml

主要使用两个 spinner 分别实现城市 省份的选择

[html]  view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent"
  5. android:orientation="vertical" >
  6. <TextView
  7. android:text="省份/直辖市"
  8. android:textSize="20dp"
  9. android:textStyle="bold"
  10. android:layout_width="fill_parent"
  11. android:layout_height="wrap_content"
  12. />
  13. <Spinner
  14. android:id="@+id/provinces"
  15. android:layout_width="fill_parent"
  16. android:layout_height="wrap_content"
  17. />
  18. <TextView
  19. android:text="市/县"
  20. android:textSize="20dp"
  21. android:textStyle="bold"
  22. android:layout_width="fill_parent"
  23. android:layout_height="wrap_content"
  24. />
  25. <Spinner
  26. android:id="@+id/city"
  27. android:layout_width="fill_parent"
  28. android:layout_height="wrap_content"
  29. />
  30. </LinearLayout>
[html]  view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <TextView  
  8.         android:text="省份/直辖市"  
  9.         android:textSize="20dp"  
  10.         android:textStyle="bold"  
  11.         android:layout_width="fill_parent"  
  12.         android:layout_height="wrap_content"  
  13.        />  
  14.     <Spinner  
  15.         android:id="@+id/provinces"  
  16.         android:layout_width="fill_parent"  
  17.         android:layout_height="wrap_content"  
  18.        />  
  19.      <TextView  
  20.         android:text="市/县"  
  21.         android:textSize="20dp"  
  22.         android:textStyle="bold"  
  23.         android:layout_width="fill_parent"  
  24.         android:layout_height="wrap_content"  
  25.        />  
  26.     <Spinner  
  27.         android:id="@+id/city"  
  28.         android:layout_width="fill_parent"  
  29.         android:layout_height="wrap_content"  
  30.         />  
  31.   
  32. </LinearLayout>  


主程序City_SelectionActivity.java

[java]  view plain copy
  1. package com.cityselection;
  2. import java.io.File;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import android.app.Activity;
  6. import android.database.Cursor;
  7. import android.database.sqlite.SQLiteDatabase;
  8. import android.os.Bundle;
  9. import android.view.View;
  10. import android.widget.AdapterView;
  11. import android.widget.AdapterView.OnItemSelectedListener;
  12. import android.widget.ArrayAdapter;
  13. import android.widget.Spinner;
  14. import android.widget.Toast;
  15. public class City_SelectionActivity extends Activity {
  16. /** Called when the activity is first created. */
  17. private File f = new File("/sdcard/weather/db_weather.db"); //数据库文件
  18. private Spinner province; //省份spinner
  19. private Spinner city; //城市spinner
  20. private List<String> proset=new ArrayList<String>();//省份集合
  21. private List<String> citset=new ArrayList<String>();//城市集合
  22. private int pro_id;
  23. @Override
  24. public void onCreate(Bundle savedInstanceState) {
  25. super.onCreate(savedInstanceState);
  26. setContentView(R.layout.main);
  27. province=(Spinner)findViewById(R.id.provinces);
  28. ArrayAdapter<String> pro_adapter=new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,getProSet());
  29. province.setAdapter(pro_adapter);
  30. province.setOnItemSelectedListener(new SelectProvince());
  31. city=(Spinner)findViewById(R.id.city);
  32. city.setOnItemSelectedListener(new SelectCity());
  33. }
  34. //选择改变状态
  35. class SelectProvince implements OnItemSelectedListener{
  36. public void onItemSelected(AdapterView<?> parent, View view,
  37. int position, long id) {
  38. // TODO Auto-generated method stub
  39. //获得省份ID
  40. pro_id=position;
  41. city.setAdapter(getAdapter());
  42. }
  43. public void onNothingSelected(AdapterView<?> arg0) {
  44. // TODO Auto-generated method stub
  45. }
  46. }
  47. //城市 选择改变状态
  48. class SelectCity implements OnItemSelectedListener{
  49. public void onItemSelected(AdapterView<?> parent, View view,
  50. int position, long id) {
  51. // TODO Auto-generated method stub
  52. String cityname=parent.getItemAtPosition(position).toString();
  53. //选择提示
  54. Toast.makeText(getApplicationContext(), cityname+" "+getCityNum(position), 2000).show();
  55. }
  56. public void onNothingSelected(AdapterView<?> arg0) {
  57. // TODO Auto-generated method stub
  58. }
  59. }
  60. /**
  61. * 返回 省份集合
  62. */
  63. public List<String> getProSet(){
  64. //打开数据库
  65. SQLiteDatabase db1 = SQLiteDatabase.openOrCreateDatabase(f, null);
  66. Cursor cursor=db1.query("provinces"nullnullnullnullnullnull);
  67. while(cursor.moveToNext()){
  68. String pro=cursor.getString(cursor.getColumnIndexOrThrow("name"));
  69. proset.add(pro);
  70. }
  71. cursor.close();
  72. db1.close();
  73. return proset;
  74. }
  75. /**
  76. * 返回 城市集合
  77. */
  78. public List<String> getCitSet(int pro_id){
  79. //清空城市集合
  80. citset.clear();
  81. //打开数据库
  82. SQLiteDatabase db1 = SQLiteDatabase.openOrCreateDatabase(f, null);
  83. Cursor cursor=db1.query("citys"null"province_id="+pro_id, nullnullnullnull);
  84. while(cursor.moveToNext()){
  85. String pro=cursor.getString(cursor.getColumnIndexOrThrow("name"));
  86. citset.add(pro);
  87. }
  88. cursor.close();
  89. db1.close();
  90. return citset;
  91. }
  92. /**
  93. * 返回适配器
  94. */
  95. public ArrayAdapter<String> getAdapter(){
  96. ArrayAdapter<String> adapter1=new ArrayAdapter(this, android.R.layout.simple_spinner_item,getCitSet(pro_id));
  97. return adapter1;
  98. }
  99. /**
  100. * 返回城市编号 以便调用天气预报api
  101. */
  102. public long getCityNum(int position){
  103. SQLiteDatabase db1 = SQLiteDatabase.openOrCreateDatabase(f, null);
  104. Cursor cursor=db1.query("citys"null"province_id="+pro_id, nullnullnullnull);
  105. cursor.moveToPosition(position);
  106. long citynum=Long.parseLong(cursor.getString(cursor.getColumnIndexOrThrow("city_num")));
  107. cursor.close();
  108. db1.close();
  109. return citynum;
  110. }
  111. }
[java]  view plain copy
  1. package com.cityselection;  
  2.   
  3. import java.io.File;  
  4. import java.util.ArrayList;  
  5. import java.util.List;  
  6.   
  7. import android.app.Activity;  
  8. import android.database.Cursor;  
  9. import android.database.sqlite.SQLiteDatabase;  
  10. import android.os.Bundle;  
  11. import android.view.View;  
  12. import android.widget.AdapterView;  
  13. import android.widget.AdapterView.OnItemSelectedListener;  
  14. import android.widget.ArrayAdapter;  
  15. import android.widget.Spinner;  
  16. import android.widget.Toast;  
  17.   
  18. public class City_SelectionActivity extends Activity {  
  19.     /** Called when the activity is first created. */  
  20.       
  21.     private File f = new File("/sdcard/weather/db_weather.db"); //数据库文件  
  22.       
  23.     private Spinner province;  //省份spinner  
  24.     private Spinner city;      //城市spinner  
  25.       
  26.     private List<String> proset=new ArrayList<String>();//省份集合  
  27.     private List<String> citset=new ArrayList<String>();//城市集合  
  28.       
  29.     private int pro_id;  
  30.     @Override  
  31.     public void onCreate(Bundle savedInstanceState) {  
  32.         super.onCreate(savedInstanceState);  
  33.         setContentView(R.layout.main);  
  34.           
  35.         province=(Spinner)findViewById(R.id.provinces);  
  36.         ArrayAdapter<String> pro_adapter=new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,getProSet());  
  37.         province.setAdapter(pro_adapter);  
  38.         province.setOnItemSelectedListener(new SelectProvince());  
  39.           
  40.         city=(Spinner)findViewById(R.id.city);  
  41.         city.setOnItemSelectedListener(new SelectCity());  
  42.     }  
  43.      
  44.     //选择改变状态  
  45.     class SelectProvince implements OnItemSelectedListener{  
  46.         public void onItemSelected(AdapterView<?> parent, View view,  
  47.                 int position, long id) {  
  48.             // TODO Auto-generated method stub  
  49.             //获得省份ID  
  50.             pro_id=position;          
  51.             city.setAdapter(getAdapter());  
  52.               
  53.         }  
  54.         public void onNothingSelected(AdapterView<?> arg0) {  
  55.             // TODO Auto-generated method stub  
  56.               
  57.         }  
  58.     }  
  59.       
  60.     //城市 选择改变状态  
  61.     class SelectCity implements OnItemSelectedListener{  
  62.         public void onItemSelected(AdapterView<?> parent, View view,  
  63.                 int position, long id) {  
  64.             // TODO Auto-generated method stub  
  65.             String cityname=parent.getItemAtPosition(position).toString();  
  66.             //选择提示  
  67.             Toast.makeText(getApplicationContext(), cityname+" "+getCityNum(position), 2000).show();  
  68.               
  69.             
  70.         }  
  71.         public void onNothingSelected(AdapterView<?> arg0) {  
  72.             // TODO Auto-generated method stub  
  73.               
  74.         }  
  75.     }  
  76.       
  77.     /** 
  78.      * 返回 省份集合 
  79.      */  
  80.     public List<String> getProSet(){  
  81.        //打开数据库   
  82.         SQLiteDatabase db1 = SQLiteDatabase.openOrCreateDatabase(f, null);  
  83.         Cursor cursor=db1.query("provinces"nullnullnullnullnullnull);  
  84.         while(cursor.moveToNext()){  
  85.             String pro=cursor.getString(cursor.getColumnIndexOrThrow("name"));  
  86.             proset.add(pro);  
  87.         }  
  88.         cursor.close();  
  89.         db1.close();  
  90.         return proset;  
  91.     }  
  92.     /** 
  93.      * 返回 城市集合 
  94.      */  
  95.     public List<String> getCitSet(int pro_id){  
  96.         //清空城市集合  
  97.         citset.clear();  
  98.        //打开数据库   
  99.         SQLiteDatabase db1 = SQLiteDatabase.openOrCreateDatabase(f, null);  
  100.         Cursor cursor=db1.query("citys"null"province_id="+pro_id, nullnullnullnull);  
  101.         while(cursor.moveToNext()){  
  102.             String pro=cursor.getString(cursor.getColumnIndexOrThrow("name"));  
  103.             citset.add(pro);  
  104.         }  
  105.         cursor.close();  
  106.         db1.close();  
  107.         return citset;  
  108.     }  
  109.     /** 
  110.      * 返回适配器 
  111.      */  
  112.     public ArrayAdapter<String> getAdapter(){  
  113.           ArrayAdapter<String> adapter1=new ArrayAdapter(this, android.R.layout.simple_spinner_item,getCitSet(pro_id));  
  114.           return adapter1;  
  115.     }  
  116.      /** 
  117.       * 返回城市编号  以便调用天气预报api 
  118.       */  
  119.     public long getCityNum(int position){  
  120.         SQLiteDatabase db1 = SQLiteDatabase.openOrCreateDatabase(f, null);  
  121.         Cursor cursor=db1.query("citys"null"province_id="+pro_id, nullnullnullnull);  
  122.         cursor.moveToPosition(position);  
  123.         long citynum=Long.parseLong(cursor.getString(cursor.getColumnIndexOrThrow("city_num")));  
  124.         cursor.close();  
  125.         db1.close();  
  126.         return citynum;  
  127.     }  
  128.       
  129. }  


实现结果:

代码下载 :http://download.csdn.net/detail/forsta/4248931

 


  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Android设备上获取用户的当前位置并获取城市,可以使用Android系统提供的LocationManager类和Geocoder类。 首先,需要在AndroidManifest.xml文件添加以下权限: ```xml <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <uses-permission android:name="android.permission.INTERNET"/> ``` 然后,在代码使用LocationManager类获取设备的当前位置: ```java LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); ``` 这里使用NETWORK_PROVIDER来获取网络位置,也可以使用GPS_PROVIDER来获取GPS位置。获取到位置后,就可以使用Geocoder类将位置转换成城市: ```java Geocoder geocoder = new Geocoder(this, Locale.getDefault()); List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1); String city = addresses.get(0).getLocality(); ``` 这里需要注意的是,getFromLocation方法需要在异步线程执行,以避免阻塞UI线程。完整的代码示例如下: ```java public class MainActivity extends AppCompatActivity { private TextView cityTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); cityTextView = findViewById(R.id.city_text_view); LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (location != null) { new GetCityTask().execute(location); } } private class GetCityTask extends AsyncTask<Location, Void, String> { @Override protected String doInBackground(Location... locations) { Geocoder geocoder = new Geocoder(MainActivity.this, Locale.getDefault()); List<Address> addresses = null; try { addresses = geocoder.getFromLocation(locations[0].getLatitude(), locations[0].getLongitude(), 1); } catch (IOException e) { e.printStackTrace(); } if (addresses != null && addresses.size() > 0) { return addresses.get(0).getLocality(); } else { return null; } } @Override protected void onPostExecute(String city) { if (city != null) { cityTextView.setText(city); } } } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值