从sdcard导入SQLite数据库到android – 没有Assets文件夹

前端之家收集整理的这篇文章主要介绍了从sdcard导入SQLite数据库到android – 没有Assets文件夹前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图从sdcard或任何外部位置导入我的sqlite数据库到我的 Android应用程序.我的应用程序需要数据库导入,以便数据库架构不会更改,但记录会根据要导入的数据库而更改.

(例如,我可能在给定时间导入具有10条记录的DatabaseA,而另一次我可能导入具有25条记录的DatabaseA.数据库A始终从同一外部位置导入).

到目前为止我使用assets文件夹看到的导入方法没有帮助.我想导入指向外部位置的数据库.

解决方法

我使用以下代码从sdcard导入我的数据库.

请注意:需要在应用程序内创建一个数据库文件夹,以便成功导入数据库.

public void importDB() {

String dir=Environment.getExternalStorageDirectory().getAbsolutePath();
File sd = new File(dir);
File data = Environment.getDataDirectory();
FileChannel source = null;
FileChannel destination = null;
String backupDBPath = "/data/com.example.mine.move/databases/A.db";
String currentDBPath = "A.db";
File currentDB = new File(sd,currentDBPath);
File backupDB = new File(data,backupDBPath);
try {
    source = new FileInputStream(currentDB).getChannel();
    destination = new FileOutputStream(backupDB).getChannel();
    destination.transferFrom(source,source.size());
    source.close();
    destination.close();
    Toast.makeText(this,"Please wait",Toast.LENGTH_SHORT).show();
} catch (IOException e) {
    e.printStackTrace();
}

此外,添加以下权限.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

如果导入不成功,请降级sdk版本或包含运行时权限.

猜你在找的Sqlite相关文章