开发者

How to populate a test database in Android?

开发者 https://www.devze.com 2023-01-08 00:12 出处:网络
I have a test class that extends ProviderTestCase2<>. I would like to populate this test class database with data from some .db files.

I have a test class that extends ProviderTestCase2<>.

I would like to populate this test class database with data from some .db files.

Is there some particular method to push some .db file into the Mock Context of a ProviderTestCase2?

O开发者_如何学Gotherwise which way is the easier to populate the database from the .db file?!

Thank you very much!!


How about copying in a pre-existing .db file from the SD Card or something similar? This is a quick piece of code that will accomplish this for you:

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();
    }
}

Hopefully this will work for your scenario

0

精彩评论

暂无评论...
验证码 换一张
取 消