我试图在设备磁盘上创建一个db文件(SQLite) - 一切正常,没有例外 - 但是文件没有创建。
添加了这些权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
代码:
public class DbHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "myAppDatabase.db";
private static final String PersistenceFolder = Environment.getExternalStorageDirectory() + File.separator + "MyApp" + File.separator;
private static final String PersistenceFilePath = PersistenceFolder + DATABASE_NAME;
public DbHandler(Context context) {
super(context, PersistenceFilePath, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
createTable1();
createTable2();
}
private void createTable1(){
// create table 1 with no exception
}
private void createTable2(){
// create table 2 with no exception
}
}
答案 0 :(得分:1)
好吧让我们这么简单下面的代码决定我是否有SD卡如果不是我们使用内部存储但它获取路径然后将该PATH传递给创建数据库的DBHelper我将发布代码以先获取PATH然后DBHelper代码
public void onAvail() {
String state = Environment.getExternalStorageState();
if (state.equals(Environment.MEDIA_MOUNTED) && (!state.equals(Environment.MEDIA_MOUNTED_READ_ONLY))) {
File removable = ContextCompat.getExternalFilesDirs(this, null)[1];
THE_PATH = String.valueOf(removable) + "/Documents/";
//System.out.println("ALL TRUE ==> " + THE_PATH);
} else {// if (state.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
THE_PATH = "";
//System.out.println("ALL FALSE ==> "+ THE_PATH);
}
}
创建DB的部分DBHelper代码
public class DBHelper扩展了SQLiteOpenHelper {
public static final String DB_NAME = THE_PATH +"PassWord";
//public static final String DB_NAME = "PassWord";
// Code Above for Internal Storage ONLY
public static final Integer DB_VERSION = 1;