Android 使用assets下的数据库文件,号码归属地查询Demo

先上图吧:
这里写图片描述

说说这个实现,查询号码归属地又两种方式,一种是网络访问,一种是本地数据库查询,这里我是选择使用本地数据库查询。

本地库查询首先得有个库,想偷懒可以点这里
库下好后,就是使用了。
首先在main目录下建一个assets目录,把库copy到这个目录。
接着就是把这个numberaddress.db copy到自己包下的database下面


/** 
 * This is a Assets Database Manager 
 * Use it, you can use a assets database file in you application 
 * It will copy the database file to "/data/data/[your application package name]/database" when you first time you use it 
 * Then you can get a SQLiteDatabase object by the assets database file  
 * @author RobinTang 
 * @time 2012-09-20 
 *  
 *  
 * How to use: 
 * 1. Initialize AssetsDatabaseManager 
 * 2. Get AssetsDatabaseManager 
 * 3. Get a SQLiteDatabase object through database file 
 * 4. Use this database object 
 *  
 * Using example: 
 * AssetsDatabaseManager.initManager(getApplication()); // this method is only need call one time 
 * AssetsDatabaseManager mg = AssetsDatabaseManager.getManager();   // get a AssetsDatabaseManager object 
 * SQLiteDatabase db1 = mg.getDatabase("db1.db");   // get SQLiteDatabase object, db1.db is a file in assets folder 
 * db1.???  // every operate by you want 
 * Of cause, you can use AssetsDatabaseManager.getManager().getDatabase("xx") to get a database when you need use a database 
 */  
public class AssetsDatabaseManager {  
    private static String tag = "AssetsDatabase"; // for LogCat  
    private static String databasepath = "/data/data/%s/database"; // %s is packageName  


    // A mapping from assets database file to SQLiteDatabase object  
    private Map<String, SQLiteDatabase> databases = new HashMap<String, SQLiteDatabase>();  

    // Context of application  
    private Context context = null;  

    // Singleton Pattern  
    private static AssetsDatabaseManager mInstance = null;  

    /** 
     * Initialize AssetsDatabaseManager 
     * @param context, context of application 
     */  
    public static void initManager(Context context){  
        if(mInstance == null){  
            mInstance = new AssetsDatabaseManager(context);  
        }  
    }  

    /** 
     * Get a AssetsDatabaseManager object 
     * @return, if success return a AssetsDatabaseManager object, else return null 
     */  
    public static AssetsDatabaseManager getManager(){  
        return mInstance;  
    }  

    private AssetsDatabaseManager(Context context){  
        this.context = context;  
    }  

    /** 
     * Get a assets database, if this database is opened this method is only return a copy of the opened database 
     * @param dbfile, the assets file which will be opened for a database 
     * @return, if success it return a SQLiteDatabase object else return null 
     */  
    public SQLiteDatabase getDatabase(String dbfile) {  
        if(databases.get(dbfile) != null){  
            Log.i(tag, String.format("Return a database copy of %s", dbfile));  
            return (SQLiteDatabase) databases.get(dbfile);  
        }  
        if(context==null)  
            return null;  

        Log.i(tag, String.format("Create database %s", dbfile));  
        String spath = getDatabaseFilepath();  
        String sfile = getDatabaseFile(dbfile);  

        File file = new File(sfile);  
        SharedPreferences dbs = context.getSharedPreferences(AssetsDatabaseManager.class.toString(), 0);  
        boolean flag = dbs.getBoolean(dbfile, false); // Get Database file flag, if true means this database file was copied and valid  
        if(!flag || !file.exists()){  
            file = new File(spath);  
            if(!file.exists() && !file.mkdirs()){  
                Log.i(tag, "Create \""+spath+"\" fail!");  
                return null;  
            }  
            if(!copyAssetsToFilesystem(dbfile, sfile)){  
                Log.i(tag, String.format("Copy %s to %s fail!", dbfile, sfile));  
                return null;  
            }  

            dbs.edit().putBoolean(dbfile, true).commit();  
        }  

        SQLiteDatabase db = SQLiteDatabase.openDatabase(sfile, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);  
        if(db != null){  
            databases.put(dbfile, db);  
        }  
        return db;  
    }  

    private String getDatabaseFilepath(){  
        return String.format(databasepath, context.getApplicationInfo().packageName);  
    }  

    private String getDatabaseFile(String dbfile){  
        return getDatabaseFilepath()+"/"+dbfile;  
    }  

    private boolean copyAssetsToFilesystem(String assetsSrc, String des){  
        Log.i(tag, "Copy "+assetsSrc+" to "+des);  
        InputStream istream = null;  
        OutputStream ostream = null;  
        try{  
            AssetManager am = context.getAssets();  
            istream = am.open(assetsSrc);  
            ostream = new FileOutputStream(des);  
            byte[] buffer = new byte[1024];  
            int length;  
            while ((length = istream.read(buffer))>0){  
                ostream.write(buffer, 0, length);  
            }  
            istream.close();  
            ostream.close();  
        }  
        catch(Exception e){  
            e.printStackTrace();  
            try{  
                if(istream!=null)  
                    istream.close();  
                if(ostream!=null)  
                    ostream.close();  
            }  
            catch(Exception ee){  
                ee.printStackTrace();  
            }  
            return false;  
        }  
        return true;  
    }  

    /** 
     * Close assets database 
     * @param dbfile, the assets file which will be closed soon 
     * @return, the status of this operating 
     */  
    public boolean closeDatabase(String dbfile){  
        if(databases.get(dbfile) != null){  
            SQLiteDatabase db = (SQLiteDatabase) databases.get(dbfile);  
            db.close();  
            databases.remove(dbfile);  
            return true;  
        }  
        return false;  
    }  

    /** 
     * Close all assets database 
     */  
    static public void closeAllDatabase(){  
        Log.i(tag, "closeAllDatabase");  
        if(mInstance != null){  
            for(int i=0; i<mInstance.databases.size(); ++i){  
                if(mInstance.databases.get(i)!=null){  
                    mInstance.databases.get(i).close();  
                }  
            }  
            mInstance.databases.clear();  
        }  
    }  
}  

这是一个前辈写的把数据库文件copy到自己程序包的database目录下的封装出处
执行的逻辑为:如果database目录下没有这个数据库文件就去copy,有则不copy
这里只需要把:

 private static String databasepath = "/data/data/%s/database"; // %s is packageName  

%s 替换成自己的程序包名就ok了

使用:

public class MainActivity extends AppCompatActivity {

    private EditText editInput;
    private TextView tv;

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

        //初始化,建议放在Application创建的时候
        AssetsDatabaseManager.initManager(this);

    }


    public void queryAddress(View view){
        PhoneNumAddress phoneNumAddress = PhoneNumberDBHelper.queryPhoneNum(editInput.getText().toString().trim());
        if (phoneNumAddress == null) {
            Toast.makeText(this,"请输入正确的手机号码",Toast.LENGTH_SHORT).show();
            return;
        }

        tv.setText("id = " + phoneNumAddress.getId() +
        " number = " + phoneNumAddress.getNumber() +
        " privince = " + phoneNumAddress.getPrivince() +
        " city = " + phoneNumAddress.getCity() +
        " telecom = " + phoneNumAddress.getTelecom());
    }

PhoneNumberDBHelper:

public  class PhoneNumberDBHelper {

    // 初始化数据库
    public static PhoneNumAddress queryPhoneNum(String num) {
        if (num.length() != 11) {
            return null;
        }
        PhoneNumAddress phoneNumAddress = new PhoneNumAddress();
        //取电话号码前7位
        num = num.substring(0, 7);

        // 获取管理对象,因为数据库需要通过管理对象才能够获取
        AssetsDatabaseManager mg = AssetsDatabaseManager.getManager();
        // 通过管理对象获取数据库
        SQLiteDatabase db = mg.getDatabase("numberaddress.db");
        // 对数据库进行操作
        Cursor cursor = db.rawQuery("select * from numberaddress where number = " + num + "", null);
        cursor.moveToFirst();
        if (!cursor.isAfterLast() && (cursor.getString(0) != null)) {
            phoneNumAddress.setId(cursor.getString(0));
            phoneNumAddress.setNumber(cursor.getString(1));
            phoneNumAddress.setPrivince(cursor.getString(2));
            phoneNumAddress.setCity(cursor.getString(3));
            phoneNumAddress.setTelecom(cursor.getString(4));
        }else{
            phoneNumAddress.setId("未知");
            phoneNumAddress.setNumber("未知");
            phoneNumAddress.setPrivince("未知");
            phoneNumAddress.setCity("未知");
            phoneNumAddress.setTelecom("未知");

        }
        cursor.close();

        return phoneNumAddress;
    }


}

源码

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值