利用小米数据库查找手机归属地

知识点:

1 数据库文件拷贝

2 使用SQLlite完成手机归属地查找


1 数据库文件拷贝

/**
	 * 将数据库拷贝到getFilesDir()中
	 * 
	 * @param dbName
	 */
	public void copyDB(String dbName) {
		InputStream in = null;
		FileOutputStream out = null;
		File file = new File(getFilesDir(), dbName);

		if (file.exists()) { //如果数据已经存在,不进行更新数据库
			return;
		}
		try {
			in = getAssets().open(dbName);
			out = new FileOutputStream(file);

			int len = 0;
			byte[] buffer = new byte[1024];
			while ((len = in.read(buffer)) != -1) {
				out.write(buffer, 0, len);
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				in.close();
				out.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

address.db放在assets中:


经过拷贝后,address.db放入在getFilesDir()+dbName(文件名address.db)中。


2 使用SQLlite完成手机归属地查找

package com.example.mobliesoft.Activity.DB;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class AddressDao {

	public static final String PATH = "data/data/com.example.mobliesoft/files/address.db";

	public String getAddress(String phonenum) {

		String address = "未知号码";

		//打开数据库
		SQLiteDatabase database = SQLiteDatabase.openDatabase(PATH, null, SQLiteDatabase.OPEN_READONLY);

		if (phonenum.matches("^1[3-8]\\d{9}$")) {
			//数据库中查找数据
			Cursor cursor = database.rawQuery(
					"select location from data2 where id=(select outkey from data1 where id=?)",
					new String[] { phonenum.substring(0, 7) });
			if (cursor.moveToNext()) {
				address = cursor.getString(0);
			}
			else
			{
				address="未知号码";
			}
			cursor.close();
		} else {
			address="请输入正确号码";
		}
		database.close();
		return address;
	}

}

卧槽,先这样吧,这块儿真心不给力啊~

你可能感兴趣的:(android,项目)