去数据库查询号码归属地
1.网络查询
2.本地的数据库--数据库写一个工具类,去查询数据库
对于现在时代能不用流量就不用啊,所以选择第二种重点是因为在安卓里面 数据库必须放在asset里面而要找到必须先初始化拷贝进去
在activity初始化的时候 加入 copyDB();方法
/**
* //path 把address.db这个数据库拷贝到data/data/《包名》/files/address.db
*/
private void copyDB() {
//只要你拷贝了一次,我就不要你再拷贝了
try {
//得到目录
File file = new File(getFilesDir(), "address.db");
if(file.exists()&&file.length()>0){
//正常了,就不需要拷贝了
Log.i(TAG, "正常了,就不需要拷贝了");
}else{
InputStream is = getAssets().open("address.db");
FileOutputStream fos = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len = 0;
while((len = is.read(buffer))!= -1){
fos.write(buffer, 0, len);
}
is.close();
fos.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
其中还有万能代码,基本上输入输出是基本搞得定
接下来的代码 查询数据库的类 可以直接复制进你的项目中
NumberAddressQueryUtils
package com.xiaoxin.MobleSafe.dao;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class NumberAddressQueryUtils {
private static String path = "data/data/com.xiaoxin.MobleSafe/files/address.db";
/**
* 传一个号码进来,返回一归属地回去
*
* @param number
* @return
*/
public static String queryNumber(String number) {
String address = number;
// path 把address.db这个数据库拷贝到data/data/《包名》/files/address.db
SQLiteDatabase database = SQLiteDatabase.openDatabase(path, null,
SQLiteDatabase.OPEN_READONLY);
// 手机号码 13 14 15 16 18
// 手机号码的正则表达式
if (number.matches("^1[34568]\\d{9}$")) {
// 手机号码
Cursor cursor = database
.rawQuery(
"select location from data2 where id = (select outkey from data1 where id = ?)",
new String[] { number.substring(0, 7) });
while (cursor.moveToNext()) {
String location = cursor.getString(0);
address = location;
}
cursor.close();
} else {
// 其他的电话号码
switch (number.length()) {
case 3:
// 110
address = "匪警号码";
break;
case 4:
// 5554
address = "模拟器";
break;
case 5:
// 10086
address = "客服电话";
break;
case 7:
//
address = "本地号码";
break;
case 8:
address = "本地号码";
break;
default:
// /处理长途电话 10
if (number.length() > 10 && number.startsWith("0")) {
// 010-59790386
Cursor cursor = database.rawQuery(
"select location from data2 where area = ?",
new String[] { number.substring(1, 3) });
while (cursor.moveToNext()) {
<span style="white-space:pre"> </span>String location = cursor.getString(0);
address = location.substring(0, location.length() - 2);
}
cursor.close();
// 0855-59790386
cursor = database.rawQuery(
"select location from data2 where area = ?",
new String[] { number.substring(1, 4) });
while (cursor.moveToNext()) {
String location = cursor.getString(0);
address = location.substring(0, location.length() - 2);
}
}
break;
}
}
return address;
}
}
数据库的问题,你可以去某宝买一个也不贵20元