操作数据库的类:
- /**
- * 程序第一初始化的时候,通过类加载器把数据库拷贝到/data/data/<包名>/目录下
- * @author Administrator
- *
- */
- public class AddressService {
- public static final String TAG="AddressService";
- Context context;
- public static final String DBNAME= "address.db";
- public AddressService(Context context) {
- this.context = context;
- }
- /**
- * 判断数据库是否存在
- * @return
- */
- public boolean isExist() {
- File file = new File(context.getFilesDir(),DBNAME);
- return file.exists();
- }
- /**
- * 拷贝数据库到系统的/data/data/<包名>/下
- * @throws Exception
- */
- public void copyDataBase() throws Exception{
- InputStream is = this.getClass().getClassLoader().getResourceAsStream("address.db");
- File file = new File(context.getFilesDir(),DBNAME);
- FileOutputStream fos = new FileOutputStream(file);
- byte[] buffer = new byte[1024];
- int len;
- while ((len = is.read(buffer))!=-1){
- fos.write(buffer, 0, len);
- };
- fos.close();
- is.close();
- }
- public String getAddress(String number){
- File file = new File(context.getFilesDir(),DBNAME);
- String address = number;
- SQLiteDatabase db = SQLiteDatabase.openDatabase(file.getAbsolutePath(), null,SQLiteDatabase.OPEN_READONLY);
- if (db.isOpen()){ // 如果数据库是打开的,就可以对数据库进行操作,操作完后记得关闭数据库
- // ^1[358]\d{9}$
- if(Pattern.compile("^1[358]\\d{9}{1}quot;).matcher(number).matches()){
- String phoneprefix7 = number.substring(0, 7);
- Log.i(TAG,phoneprefix7);
- Cursor cursor= db.rawQuery("select city from info where mobileprefix=?", new String[]{phoneprefix7});
- if(cursor.moveToFirst()){
- address = cursor.getString(0);
- }
- cursor.close();
- }
- else{
- Cursor cursor= null;
- /* 固定电话 本地号码7位 ,8位
- 长途号码 带区号 区号有3位和4位的
- 10位 3位区号+7位电话号码
- 11位 4位区号+7位电话 3位区号+8位电话
- 12位 4位区号+8位电话*/
- switch (number.length()) {
- case 7:
- address = context.getApplicationContext().getResources().getString(R.string.local);
- break;
- case 8:
- address = context.getApplicationContext().getResources().getString(R.string.local);
- break;
- case 10:
- String numberprefix3 = number.substring(0, 3);
- cursor= db.rawQuery("select city from info where area=?", new String[]{numberprefix3});
- if(cursor.moveToFirst()){
- address = cursor.getString(0);
- }
- cursor.close();
- break;
- case 11:
- String numberprefix_3 = number.substring(0, 3);
- String numberprefix_4 = number.substring(0, 4);
- cursor= db.rawQuery("select city from info where area=? or area = ?", new String[]{numberprefix_3,numberprefix_4});
- if(cursor.moveToFirst()){
- address = cursor.getString(0);
- }
- cursor.close();
- break;
- case 12:
- String numberprefix4 = number.substring(0, 4);
- cursor= db.rawQuery("select city from info where area=?", new String[]{numberprefix4});
- if(cursor.moveToFirst()){
- address = cursor.getString(0);
- }
- cursor.close();
- break;
- case 4:
- address = context.getApplicationContext().getResources().getString(R.string.emulator);
- break;
- }
- }
- db.close();
- }
- return address;
- }
- }
