我正面临着一种关于使用 Android 访问资产的诅咒。我正在使用 NetBeans 6.9.1 并在 2.3 Android 虚拟设备上进行测试。我正在尝试访问存储在资产文件夹中的数据库文件(“database.db”)(尽管我不得不自己创建该目录,因为它甚至不存在于我的项目文件夹中),我只是在失去寻找解决方案超过 3 天后无法做到这一点。这里总结一下我的悲惨过程:
- 我在我的 NetBeans 项目目录中创建了一个名为“assets”的目录(就在“res”或“src”文件夹所在的位置)。
- 我已经复制了里面的“database.db”文件,甚至还有一个“sample.txt”,当我正在测试所有可能的人时,我也将它存储在“assets/sub”子目录中。
我有一个继承自“SQLiteOpenHelper”的类,我只是试图访问我的数据库文件,并且在看到这几乎是不可能的之后,我只是想看看我的资产文件夹包含什么:
public class DataBaseHelper extends SQLiteOpenHelper{ private static String DB_PATH = "/data/data/org.me.androidbt/databases/"; private static String DB_NAME = "database.db"; private SQLiteDatabase myDataBase; private final Context myContext; public DataBaseHelper(Context context) { super(context, DB_NAME, null, 1); this.myContext = context; } private void myFunction() throws IOException{ //Firs try, explodes terribly at the first line InputStream is = myContext.getAssets().open("sub/sample.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line = null; int number = 0; while ((line = br.readLine()) != null) { // Just used to check the "line" value when debugging number++; } br.close(); // Second try, didn't explodes AssetManager mngr = myContext.getResources().getAssets(); String[] str = mngr.list(""); // String only contains three elements: "images", "sounds" and "webkit" // (an there aren't such things in my assets folder) // Real try to open the DB, dies horribly and blowns up my PC InputStream myInput = myContext.getAssets().open(DB_NAME);
我也尝试从 MainActivity 本身访问它:
try{
AssetManager mng = this.getAssets();
String[] str = mng.list("");
// The same three elements...
// And this explodes in a nuclear toxic cloud that kills a thousand birds
InputStream is = this.getAssets().open("sub/sample.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
int number = 0;
while ((line = br.readLine()) != null) {
number++;
}
br.close();
}catch(Exception e){
// Life is sad...
}
现在,一些问题:我做错了什么?我的资产文件夹是否正确放置?我的文件被正确复制了吗?我的代码是否正确放置?