我试图从sdcard或任何外部位置导入我的sqlite数据库到我的
Android应用程序.我的应用程序需要数据库导入,以便数据库架构不会更改,但记录会根据要导入的数据库而更改.
(例如,我可能在给定时间导入具有10条记录的DatabaseA,而另一次我可能导入具有25条记录的DatabaseA.数据库A始终从同一外部位置导入).
解决方法
我使用以下代码从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版本或包含运行时权限.