我把我的数据库字段放在"assets"文件夹中.并使用此博客中的代码将数据库复制到"/ data/data/my_packname/databases /",(此复制代码我在运行此应用程序时在onCreate()方法中运行)然后使用select*from ..获取数据 但它给了我一个例外:没有这样的表.
有人告诉我,如果我试图在SQLiteOpenHelper的onCreate()中复制文件,那就太晚了.因此复制文件代码无法复制完整的文件.
所以我需要先使用adb或ddms拉数据库?
那么,任何人都可以教我如何使用自己的数据库?你能告诉我这个设置吗?
我已经使用了该博客文章中的说明,并在正确的轨道上发现它们通过不必要的扩展使问题严重复杂化SQLiteOpenHelper
.做以下事情我运气好多了:
创建一个实用程序类,通过将静态数据库从资产复制到正确的目录中来创建静态数据库,但不会因为SQLiteOpenHelper格式而陷入困境.
使用相同的实用程序类通过使用打开db 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, 0, 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); } }