有人告诉我,如果我试图在sqliteOpenHelper的onCreate()中复制文件,那就太晚了.因此复制文件代码无法复制完整的文件.
所以我需要先使用adb或ddms拉数据库吗?
那么,任何人都可以教我如何使用我自己的数据库?
你能告诉我这个设置吗?
有人告诉我,如果我试图在sqliteOpenHelper的onCreate()中复制文件,那就太晚了.因此复制文件代码无法复制完整的文件.
所以我需要先使用adb或ddms拉数据库吗?
那么,任何人都可以教我如何使用我自己的数据库?
你能告诉我这个设置吗?
>创建一个实用程序类,通过将静态数据库从资产复制到正确的目录中来创建静态数据库,但不会因为sqliteOpenHelper格式而陷入困境.
>使用相同的实用程序类通过使用sqliteDatabase.openDatabase()打开数据库
编辑:这是我创建的这个实用程序类的一个版本;它不是很完整,但你会得到漂移.
public class DbUtils { private static final String DB_PATH = "/data/data/com.mypackage.myapp/databases/"; private static final String DB_NAME = "my.db"; public static void createDatabaseIfNotExists(Context context) throws IOException { boolean createDb = false; File dbDir = new File(DB_PATH); File dbFile = new File(DB_PATH + DB_NAME); if (!dbDir.exists()) { dbDir.mkdir(); createDb = true; } else if (!dbFile.exists()) { createDb = true; } else { // Check that we have the latest version of the db boolean doUpgrade = false; // Insert your own logic here on whether to upgrade the db; I personally // just store the db version # in a text file,but you can do whatever // you want. I've tried MD5 hashing the db before,but that takes a while. // If we are doing an upgrade,basically we just delete the db then // flip the switch to create a new one if (doUpgrade) { dbFile.delete(); createDb = true; } } if (createDb) { // Open your local db as the input stream InputStream myInput = context.getAssets().open(DB_NAME); // Open the empty db as the output stream OutputStream myOutput = new FileOutputStream(dbFile); // transfer bytes from the inputfile to the outputfile byte[] buffer = new byte[1024]; int length; while ((length = myInput.read(buffer)) > 0) { myOutput.write(buffer,length); } // Close the streams myOutput.flush(); myOutput.close(); myInput.close(); } } public static sqliteDatabase getStaticDb() { return sqliteDatabase.openDatabase(DB_PATH + DB_NAME,null,sqliteDatabase.OPEN_READONLY); } }