Android 自定义Android ORM 框架greenDAO数据库文件的路径

时间:2021-12-15 01:49:03
import android.content.Context;
import android.content.ContextWrapper;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase; import com.tbc.android.defaults.app.business.cache.AppUserCache;
import com.tbc.android.defaults.app.utils.AppPathUtil;
import com.tbc.android.mc.storage.ApplicationCache; import java.io.File; /**
* Created by Doraemon
* Date: 16/5/12
* Time: 09:22
* Summary:该类主要用于基于GreenDao框架自定义数据库路径
*/
public class GreenDaoContext extends ContextWrapper { private String currentUserId;
private Context mContext; public GreenDaoContext() {
super(ApplicationCache.context);
this.mContext = ApplicationCache.context;
this.currentUserId = AppUserCache.userInfo.getUserId();
} /**
* 获得数据库路径,如果不存在,则创建对象
*
* @param dbName
*/
@Override
public File getDatabasePath(String dbName) {
File baseFile = AppPathUtil.getDbCacheDir(mContext);
StringBuffer buffer = new StringBuffer();
buffer.append(baseFile.getPath());
buffer.append(File.separator);
buffer.append(currentUserId);
buffer.append(File.separator);
buffer.append(dbName);
return new File(buffer.toString());
} /**
* 重载这个方法,是用来打开SD卡上的数据库的,android 2.3及以下会调用这个方法。
*
* @param name
* @param mode
* @param factory
*/
@Override
public SQLiteDatabase openOrCreateDatabase(String name, int mode,
SQLiteDatabase.CursorFactory factory) {
SQLiteDatabase result = SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), factory);
return result;
} /**
* Android 4.0会调用此方法获取数据库。
*
* @param name
* @param mode
* @param factory
* @param errorHandler
* @see android.content.ContextWrapper#openOrCreateDatabase(java.lang.String, int,
* android.database.sqlite.SQLiteDatabase.CursorFactory,
* android.database.DatabaseErrorHandler)
*/
@Override
public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory,
DatabaseErrorHandler errorHandler) {
SQLiteDatabase result = SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), factory); return result;
} }

自定义一个context,然后在获取helper时,将自定义的context传入,如下:

DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(new GreenDaoContext(), "app.db", null);
SQLiteDatabase db = helper.getWritableDatabase();
// 注意:该数据库连接属于 DaoMaster,所以多个 Session 指的是相同的数据库连接。
DaoMaster daoMaster = new DaoMaster(db);
DaoSession daoSession = daoMaster.newSession();