读取assets目录下的数据库文件

本文介绍了如何在Android应用中从assets目录读取数据库文件laws.db,通过InputStream和FileOutputStream实现文件复制,并在DBHelper类中执行SQL查询。
摘要由CSDN通过智能技术生成

Android开发系列(十七):读取assets目录下的数据库文件 – 源码巴士

数据库文件不像 assets 目录下的 htm 和 图片 能直接使用,需要复制出来才能使用。

CatalogActivity.java

String filename_db = "laws.db";
String path_db = getFilesDir().getPath() + File.separator + filename_db;

void copyDB() {
    try {
        InputStream IS = getAssets().open(filename_db);
        FileOutputStream FOS = new FileOutputStream(path_db);
        byte[] buffer = new byte[1024];
        int count;
        while ((count = IS.read(buffer)) > 0) {
            FOS.write(buffer, 0, count);
        }
        FOS.flush();
        FOS.close();
        IS.close();
    } catch (Exception e) {
        Log.e(Thread.currentThread().getStackTrace()[2] + "", e.toString());
        Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
    }
}


copyDB();
DBHelper helper = new DBHelper(this);
Cursor cursor = helper.catalog(s);

DBHelper.java

public class DBHelper extends SQLiteOpenHelper {

	static String DATABASE_NAME = CatalogActivity.path_db;
    static int VERSION = 2;
    private SQLiteDatabase db;

    public DBHelper(Context context) {
		super(context, DATABASE_NAME, null, VERSION);
	}

    @Override
	    public void onCreate(SQLiteDatabase db) {		
    		this.db = db;
	}

    public Cursor catalog(String s) {
		db = getWritableDatabase();
		Cursor c;
		if (s.equals(""))
			c = db.query("catalog", null, null, null, null, null, "_id asc");
		else
			c = db.query("catalog", null, "lawName LIKE '%" + s + "%'", null, null, null, "_id asc");
		return c;
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值