前言
在新建数据库sqlite的时候,我们已经知道了数据库默认路径为/data/data/com.example.pei.textdemo/databases/test_demo.db
那么,如果我们想在创建数据库时,自定义一个自己的路径该如何处理呢,需要涉及到三步自定义Context,重写sqlite存储路径
修改继承于SQLiteOpenHelper的DBOpenHelper类
数据库的调用
下面就来讲讲具体操作。
一.自定义Context,重写sqlite存储路径
我们在创建数据库的时候,会涉及到一个类SQLiteOpenHelper,一般建数据库的时候,都要继承SQLiteOpenHelper实现一个自己的helper类,这里,我写一个自己的helper来继承SQLiteOpenHelper,部分代码如下:public class DBOpenHelper extends SQLiteOpenHelper{
......
}
然后在DBOpenHelper这个类中,我们会有两个构造方法public DBOpenHelper(Context context) {
this(context, DB_NAME, null, 1);
this.mContext= context;
}
public DBOpenHelper(Context context, String dbName, SQLiteDatabase.CursorFactory factory, int version) {
super(context, dbName, factory, version);
}
其中 mContext为Context,Context类会涉及到sqlite的储存路径,为了自定义数据库路径,我们需要实现一个自己的context,来自定义数据库路径,然而Context有一个子类ContextWrapper,可以方便用户对Context进行自定义,看源码中ContextWrapper继承关系如下:/**
* Proxying implementation of Context that simply delegates all of its calls to
* another Context. Can be subclassed to modify behavior without changing
* the original Context.
*/
public class ContextWrapper extends Context {
Context mBase;
public ContextWrapper(Context base) {
mBase = base;
}
那么,我们就写一个类ContextWrapper来继承ContextWrapper实现自己的context,代码如下:package com.example.pei.textdemo.sqlite;
import android.content.Context;
import android.content.ContextWrapper;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import com.example.pei.textdemo.util.SDCardUtil;
import java.io.File;
/**
* Title:
* Description:
*
* Created by pei
* Date: 2017/11/20
*/
public class DataBaseCont