2010-07-15 36 views
2

我有一个测试类,它扩展了ProviderTestCase2 <>。如何在Android中填充测试数据库?

我想用一些.db文件的数据填充这个测试类数据库。

是否有某种方法将某些.db文件推送到ProviderTestCase2的模拟上下文中?

否则哪种方式更容易从.db文件填充数据库?

非常感谢!

回答

0

如何从SD卡或类似的东西中复制预先存在的.db文件?这是一个快速的代码,将做到这一点对你:

private void importDBFile(File importDB) { 
    String dataDir = Environment.getDataDirectory().getPath(); 
    String packageName = getPackageName(); 

    File importDir = new File(dataDir + "/data/" + packageName + "/databases/"); 
    if (!importDir.exists()) { 
     Toast.makeText(this, "There was a problem importing the Database", Toast.LENGTH_SHORT).show(); 
     return; 
    } 

    File importFile = new File(importDir.getPath() + "/" + importDB.getName()); 

    try { 
     importFile.createNewFile(); 
     copyDB(importDB, importFile); 
     Toast.makeText(this, "Import Successful", Toast.LENGTH_SHORT).show(); 
    } catch (IOException ex) { 
     Toast.makeText(this, "There was a problem importing the Database", Toast.LENGTH_SHORT).show(); 
    } 
} 

private void copyDB(File from, File to) throws IOException { 
    FileChannel inChannel = new FileInputStream(from).getChannel(); 
    FileChannel outChannel = new FileOutputStream(to).getChannel(); 
    try { 
     inChannel.transferTo(0, inChannel.size(), outChannel); 
    } finally { 
     if (inChannel != null) 
      inChannel.close(); 
     if (outChannel != null) 
      outChannel.close(); 
    } 
} 

希望这会为您的方案

工作
相关问题