我有一个代码在sdcard中使用数据库,它在Android 2.3设备中运行良好但在android 4设备中无法工作,在android 2.3中创建一个数据库并在sdcard上的路径上打开,在android 4中有一个数据库在手机中的应用程序的默认datadir中创建或打开。代码低于......
public class dBeeHelper extends SQLiteOpenHelper {
public final static String DATABASE_NAME = "data.db";
private final static int DATABASE_VERSION = 59;
public static final String DATABASE_FILE_PATH = Environment.getExternalStorageDirectory().toString();
public static tables db = new tables();
private Context mcontext;
public dBeeHelper(Context context) {
super(new ContextWrapper(context) {
public SQLiteDatabase openOrCreateDatabase(String name,
int mode, SQLiteDatabase.CursorFactory factory) {
// allow database directory to be specified
File dir = new File(DATABASE_FILE_PATH + "/Manager/");
if(!dir.exists()) {
dir.mkdirs();
}
Manager manager = ((Manager)getApplicationContext());
if (dir.canWrite()){
manager.setDbLocation(dataFiles.Location.SdCard);
}else{
manager.setDbLocation(dataFiles.Location.Phone);
}
return SQLiteDatabase.openDatabase( DATABASE_FILE_PATH + "/Manager/" + DATABASE_NAME, null,
SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.CREATE_IF_NECESSARY);
}
}, DATABASE_NAME, null, DATABASE_VERSION);
this.mcontext = context;
}
当我调试应用程序时,在Android 2.3中会触发openOrCreateDatabase,在android 4中它不会被触发!
谢谢!
答案 0 :(得分:0)
问题解决了!我改变了构造函数,它也在android 4中工作。 下面的代码已更改。
private static Manager manager;
public dBeeHelper(Context context) {
super(context, getpath(context) + DATABASE_NAME, null, DATABASE_VERSION);
this.mcontext = context;
}
public static String getpath(Context context){
manager = (Manager) new ContextWrapper(context).getApplicationContext();
String path = Environment.getExternalStorageDirectory() + "/" + "Manager";
File dir = new File(path);
if(!dir.exists()) {
if (dir.canWrite()){
dir.mkdirs();
}else{
manager.setDbLocation(dataFiles.Location.Phone);
return "";
}
}
manager.setDbLocation(dataFiles.Location.SdCard);
path = path + "/";
return path ;
}