android实现省市查询

1.在安卓项目中res文件夹创建raw文件夹

将city.db添加到raw文件夹下


数据库文件在这里下载:mojicity.db


2.用文件流将raw下的数据库导入到data/data下就可以随心所欲的操作了

package com.pw.weather.db; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Environment; import com.pw.weather.R; import java.io.; import java.util.ArrayList; import java.util.List; /* * FileName:weather * Description: * Created by:pengwei * date:2014/9/7 15:55 / public class CityDB { private static CityDB instance; private SQLiteDatabase db; private Context context; private final static String TABLE_PROVINCE = "PROVINCE"; private final static String TABLE_CITY = "CITY"; private final static String DB_NAME = "city.db"; public static String DB_PATH; private CityDB(Context context) { this.context = context; DB_PATH = "/data" + Environment.getDataDirectory().getAbsolutePath() + "/" + context.getPackageName(); this.importDB(); } /* * 模糊查询城市名 * 分别根据城市名,城市名拼音,城市名拼音简写模糊查询 * @param key * @return */ public List searchCity(String key) { List list = new ArrayList(); String likeKey = "%" + key + "%"; Cursor cursor = db.query(TABLECITY, null, "cityname like ? or pycityname like ? or pyshort=? ", new String[]{likeKey, likeKey, key}, null, null, null, null); while (cursor.moveToNext()) { list.add(cursor.getString(cursor.getColumnIndex("cityname"))); } return list; } //单例模式 public static CityDB getInstance(Context context) { if (null == instance) { instance = new CityDB(context); } return instance; } //从raw下导入数据库文件到/data/date/包名/databases下 private void importDB() { String dbFile = DBPATH + "/" + DBNAME; if (!new File(dbFile).exists()) { InputStream is = context.getResources().openRawResource(R.raw.city); try { FileOutputStream fos = new FileOutputStream(dbFile); byte[] buffer = new byte[2048]; int count = 0; while ((count = is.read(buffer)) != -1) { fos.write(buffer, 0, count); } fos.close(); is.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } db = context.openOrCreateDatabase(dbFile, Context.MODEPRIVATE, null); } }

3.上面我就写了一个模糊查询城市名的,查询省份的自己补全吧。

数据库结构如下