Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 三級聯動選擇城市:XML 資料匯入 SQLite 與 IntentService 背景服務

編輯:關於 Android 開發

用一份 XML 資料,做出一個能用的三級聯動城市選擇器

要做省/市/區的三級聯動,最麻煩的往往不是 UI,而是資料從哪裡來、怎麼放。這篇的整體思路是:準備一份行政區 XML → 用背景服務解析並灌進 SQLite → 在三個 Spinner 之間做連動查詢。資料準備好之後,聯動本身就只是幾個 rawQuery 的事。

一、準備資料來源

這裡用的是一份 loclist.xml,結構是四層嵌套:CountryRegion(國家)→ State(省/直轄市)→ City(市)→ Region(區/縣),每個節點都帶有 Name 與 Code 兩個屬性。

<CountryRegion Name="中國" Code="1">
  <State Name="北京" Code="11">
    <City Name="東城" Code="1" />
    <City Name="西城" Code="2" />
    <City Name="朝陽" Code="5" />
    ...
  </State>
  <State Name="河北" Code="13">
    <City Name="石家莊" Code="1">
      <Region Name="長安區" Code="2" />
      <Region Name="橋東區" Code="3" />
      ...
    </City>
    ...
  </State>
  ...
</CountryRegion>

上面只列出部分結構示意,完整的行政區清單很長(涵蓋各省、直轄市、自治區與港澳地區),可直接取用文末 GitHub 專案中的 res/xml/loclist.xml。原始檔案還包含國外資料,實作時把不需要的部分刪掉即可。

二、建立資料庫

依照 XML 的四層結構,設計 country、province、city、area 四張表,子層級用外碼欄位往上關聯:

package com.aspros.cityselect;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * 建立資料庫
 */
public class DatabaseHelper extends SQLiteOpenHelper {

    private static final String CREATE_COUNTRY = "CREATE TABLE country ( "
            + "id TEXT, "
            + "countryName TEXT "
            + ")";

    private static final String CREATE_PROVINCE = "CREATE TABLE province ( "
            + "id TEXT, "
            + "countryId TEXT, "
            + "provinceName TEXT"
            + ")";

    private static final String CREATE_CITY = "CREATE TABLE city ( "
            + "id TEXT, "
            + "provinceId TEXT, "
            + "cityName TEXT"
            + ")";

    private static final String CREATE_AREA = "CREATE TABLE area ( "
            + "id TEXT, "
            + "provinceId TEXT, "
            + "cityId TEXT, "
            + "areaName TEXT"
            + ")";

    private Context mContext;

    public DatabaseHelper(Context context, String name,
                          SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
        mContext = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_COUNTRY);
        db.execSQL(CREATE_PROVINCE);
        db.execSQL(CREATE_CITY);
        db.execSQL(CREATE_AREA);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }
}

三、用 IntentService 把 XML 灌進資料庫

解析幾千筆節點再逐筆 insert,放在主執行緒會卡住畫面,所以交給背景服務處理。這裡用 IntentService,因為它天生就在自己的 worker 執行緒上跑,做完就會自己銷毀,不必手動管理生命週期;用一般的 Service 當然也可以,看你習慣。

解析的部分走 XmlResourceParser,逐個事件往下走,遇到 CountryRegion、State、City、Region 這四種標籤時分別取值並寫入對應的表。注意這裡刻意保留「上一層的 Code」作為當前節點的外碼,這正是後續聯動查詢能成立的原因。

package com.aspros.cityselect;

import android.app.IntentService;
import android.content.Intent;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.database.sqlite.SQLiteDatabase;
import android.widget.Toast;

public class LoadDataService extends IntentService {

    private DatabaseHelper dbHelp;
    private SQLiteDatabase db;

    private String countryName, countryCode;
    private String provinceName, provinceCode;
    private String cityName, cityCode;
    private String areaName, areaCode;

    public LoadDataService() {
        super("LoadDataService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        dbHelp = new DatabaseHelper(this, "countryList.db", null, 1);
        db = dbHelp.getWritableDatabase();
        try {
            // 取得 Resources 資源
            Resources r = getResources();
            // 透過 Resources 取得 XmlResourceParser 實例
            XmlResourceParser xrp = r.getXml(R.xml.loclist);
            while (xrp.getEventType() != XmlResourceParser.END_DOCUMENT) {
                if (xrp.getEventType() == XmlResourceParser.START_TAG) {
                    String name = xrp.getName();
                    if (name.equals("CountryRegion")) {
                        countryName = xrp.getAttributeValue(null, "Name");
                        countryCode = xrp.getAttributeValue(null, "Code");
                        db.execSQL("insert into country values(?,?)",
                                new String[]{countryCode, countryName});
                    }
                    if (name.equals("State")) {
                        provinceCode = xrp.getAttributeValue(null, "Code");
                        provinceName = xrp.getAttributeValue(null, "Name");
                        db.execSQL("insert into province values(?,?,?)",
                                new String[]{provinceCode, countryCode, provinceName});
                    }
                    if (name.equals("City")) {
                        cityCode = xrp.getAttributeValue(null, "Code");
                        cityName = xrp.getAttributeValue(null, "Name");
                        db.execSQL("insert into city values(?,?,?)",
                                new String[]{cityCode, provinceCode, cityName});
                    }
                    if (name.equals("Region")) {
                        areaCode = xrp.getAttributeValue(null, "Code");
                        areaName = xrp.getAttributeValue(null, "Name");
                        db.execSQL("insert into area values(?,?,?,?)",
                                new String[]{areaCode, provinceCode, cityCode, areaName});
                    }
                }
                xrp.next();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 資料載入完成後提示
        Toast.makeText(LoadDataService.this, "LoadData Finished", Toast.LENGTH_SHORT).show();
    }
}

四、主畫面

版面用一個 LinearLayout:上方擺 TextView 顯示選好的詳細地址,下面的按鈕和 ScrollView 只是初期用來手動觸發匯入、印出資料做檢查,正式版可以刪掉。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:orientation="vertical"
        android:id="@+id/select_address">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/address_show"
            android:text="XXXX" />
    </LinearLayout>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/loadData"
        android:text="匯入資料" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/showCity"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </ScrollView>
</LinearLayout>

MainActivity 裡做三件事:綁定地址區域的點擊事件並用 startActivityForResult 跳去選擇頁、在 onCreate 中啟動 LoadDataService、在 onActivityResult 中接收回傳的省/市/區字串。

package com.aspros.cityselect;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private TextView address_show;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        address_show = (TextView) findViewById(R.id.address_show);

        // 點擊選擇詳細地址
        findViewById(R.id.select_address).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(MainActivity.this, Address_Select.class);
                startActivityForResult(i, 1);   // 等待返回資料
            }
        });

        // 啟動後台服務載入資料
        Intent is = new Intent(this, LoadDataService.class);
        startService(is);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {
                    super.onActivityResult(requestCode, resultCode, data);
                    String provinceStr = data.getStringExtra("provinceStr");
                    String cityStr = data.getStringExtra("cityStr");
                    String areaStr = data.getStringExtra("areaStr");
                    address_show.setText("省:" + provinceStr
                            + "|城市:" + cityStr
                            + "|區:" + areaStr);
                }
                break;
            default:
                break;
        }
    }
}

五、地址選擇頁與聯動邏輯

選擇頁放三個並排的 Spinner 分別對應省、市、區,下面一顆確定鈕負責把結果打包回傳。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="詳細地址:"
        android:textSize="20dp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Spinner
            android:id="@+id/provinces"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content" />

        <Spinner
            android:id="@+id/city"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content" />

        <Spinner
            android:id="@+id/area"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <Button
            android:id="@+id/back_address"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="確定" />
    </LinearLayout>
</LinearLayout>

聯動的核心寫在 onItemSelected 裡:選省 → 依 provinceId 查城市並重設 city 的 adapter;選市 → 依 provinceId 加 cityId 查區縣,若查不到(例如部分直轄市沒有下一層)就把第三個 Spinner 隱藏起來。三個資料類別都重寫了 toString(),這樣 ArrayAdapter 才能直接把名稱顯示在下拉框裡。

package com.aspros.cityselect;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

import java.util.ArrayList;
import java.util.List;

public class Address_Select extends Activity
        implements AdapterView.OnItemSelectedListener, View.OnClickListener {

    private DatabaseHelper dbHelp;
    private SQLiteDatabase db;

    private List<provinceInfo> provinceList = new ArrayList<provinceInfo>();
    private List<cityInfo> cityList = new ArrayList<cityInfo>();
    private List<areaInfo> areaList = new ArrayList<areaInfo>();

    private Spinner spinnerProvince;
    private Spinner spinnerCity;
    private Spinner spinnerArea;

    private String provinceId = null;
    private String cityId = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.address_select);

        dbHelp = new DatabaseHelper(this, "countryList.db", null, 1);
        db = dbHelp.getWritableDatabase();

        spinnerProvince = (Spinner) findViewById(R.id.provinces);
        spinnerCity = (Spinner) findViewById(R.id.city);
        spinnerArea = (Spinner) findViewById(R.id.area);

        // 載入省份
        ArrayAdapter<provinceInfo> adapter = new ArrayAdapter<provinceInfo>(
                this, R.layout.support_simple_spinner_dropdown_item, getProvinceList());
        spinnerProvince.setAdapter(adapter);
        spinnerProvince.setOnItemSelectedListener(this);

        // 部分直轄市沒有區縣,預設先隱藏第三層
        spinnerArea.setVisibility(View.INVISIBLE);

        findViewById(R.id.back_address).setOnClickListener(this);
    }

    // 監聽選項事件
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        switch (parent.getId()) {
            case R.id.provinces:
                provinceId = provinceList.get(position).getId();
                ArrayAdapter<cityInfo> cityAdapter = new ArrayAdapter<cityInfo>(
                        this, R.layout.support_simple_spinner_dropdown_item,
                        getCityList(provinceId));
                spinnerCity.setAdapter(cityAdapter);
                spinnerCity.setOnItemSelectedListener(this);
                break;
            case R.id.city:
                cityId = cityList.get(position).getId();
                if (getAreaList(provinceId, cityId).size() > 0) {
                    spinnerArea.setVisibility(View.VISIBLE);
                    ArrayAdapter<areaInfo> areaAdapter = new ArrayAdapter<areaInfo>(
                            this, R.layout.support_simple_spinner_dropdown_item,
                            getAreaList(provinceId, cityId));
                    spinnerArea.setAdapter(areaAdapter);
                } else {
                    spinnerArea.setVisibility(View.INVISIBLE);
                }
                break;
            case R.id.area:
                break;
            default:
                break;
        }
    }

    // 載入省份資料
    private List<provinceInfo> getProvinceList() {
        Cursor cursor = db.rawQuery("select * from province", null);
        while (cursor.moveToNext()) {
            provinceInfo pi = new provinceInfo();
            pi.setId(cursor.getString(cursor.getColumnIndex("id")));
            pi.setProvinceName(cursor.getString(cursor.getColumnIndex("provinceName")));
            provinceList.add(pi);
        }
        cursor.close();
        return provinceList;
    }

    // 依省份 id 取得城市
    private List<cityInfo> getCityList(String provinceId) {
        cityList = new ArrayList<cityInfo>();
        Cursor cursor = db.rawQuery("select * from city where provinceId=?",
                new String[]{provinceId});
        while (cursor.moveToNext()) {
            cityInfo ci = new cityInfo();
            ci.setId(cursor.getString(cursor.getColumnIndex("id")));
            ci.setCityName(cursor.getString(cursor.getColumnIndex("cityName")));
            cityList.add(ci);
        }
        cursor.close();
        return cityList;
    }

    // 依省份 id 與城市 id 取得區縣
    private List<areaInfo> getAreaList(String provinceId, String cityId) {
        areaList = new ArrayList<areaInfo>();
        if (provinceId != null && cityId != null) {
            Cursor cursor = db.rawQuery(
                    "select * from area where provinceId=? and cityId=?",
                    new String[]{provinceId, cityId});
            while (cursor.moveToNext()) {
                areaInfo ai = new areaInfo();
                ai.setId(cursor.getString(cursor.getColumnIndex("id")));
                ai.setAreaName(cursor.getString(cursor.getColumnIndex("areaName")));
                areaList.add(ai);
            }
            cursor.close();
        }
        return areaList;
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_address:
                Intent i = new Intent();
                i.putExtra("provinceStr", spinnerProvince.getSelectedItem().toString());
                i.putExtra("cityStr", spinnerCity.getSelectedItem().toString());
                i.putExtra("areaStr", spinnerArea.getSelectedItem().toString());
                setResult(RESULT_OK, i);
                finish();
                break;
            default:
                break;
        }
    }

    private class provinceInfo {
        String id;
        String provinceName;

        public void setId(String id) { this.id = id; }
        public void setProvinceName(String provinceName) { this.provinceName = provinceName; }
        public String getId() { return id; }
        public String getProvinceName() { return provinceName; }

        // 重寫 toString,才能把名稱填進下拉框
        @Override
        public String toString() { return provinceName; }
    }

    private class cityInfo {
        String id;
        String cityName;

        public void setId(String id) { this.id = id; }
        public void setCityName(String cityName) { this.cityName = cityName; }
        public String getId() { return id; }
        public String getCityName() { return cityName; }

        @Override
        public String toString() { return cityName; }
    }

    private class areaInfo {
        String id;
        String areaName;

        public void setId(String id) { this.id = id; }
        public void setAreaName(String areaName) { this.areaName = areaName; }
        public String getId() { return id; }
        public String getAreaName() { return areaName; }

        @Override
        public String toString() { return areaName; }
    }
}

幾個實作上的經驗

第一,資料一定要在背景服務裡一次建好,不要等使用者點開選擇頁才現場解析 XML,那樣第一次進入會明顯卡頓。第二,第三層 Spinner 務必保留「隱藏」的處理,直轄市這種沒有下游客層級的情況很常見,否則確定鈕會拿到空字串。第三,Cursor 用完記得 close,否則在多次查詢下容易觸發 Cursor 洩漏的警告。

完整源碼(含 loclist.xml 全部資料):https://github.com/aspros-luo/CitySelect

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved