我正面临一种关于使用 Android 访问 Assets 的诅咒。我正在使用 NetBeans 6.9.1 并在 2.3 Android 虚拟设备上进行测试。我正在尝试访问存储在 Assets 文件夹中的数据库文件(“database.db”)(尽管我不得不自己创建目录,因为它甚至不存在于我的项目文件夹中)而且我只是在寻找解决方案超过 3 天后无法做到这一点。这里总结一下我的悲惨过程:
- 我在我的 NetBeans 项目目录中创建了一个名为“assets”的目录(就在“res”或“src”文件夹所在的位置)。
- 我已经复制了“database.db”文件,甚至还有一个“sample.txt”,我也将其存储在“assets/sub”子目录中,因为我正在测试一切可能的人为可能。
我有一个继承自“SQLiteOpenHelper”的类,我只是想尝试访问我的数据库文件,在发现这几乎不可能之后,我只是想看看我的 Assets 文件夹包含什么:
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...
}
现在,有些问题:我做错了什么?我的 Assets 文件夹是否正确放置?我的文件被正确复制了吗?我的代码是否正确放置?
最佳答案
修复:
在您的项目根目录下创建一个名为“assets”的目录(与 AndroidManifest.xml 所在的目录相同)
在/nbproject/project.properties中,更改
*添加这两行(它不会存在)*
assets.dir= Assets assets.available=true
在/nbproject/build-impl.xml 中,
“if=assets.available”目标中有一行内容为
需要改成
就是这样——您应该已经准备就绪,您的应用程序应该可以访问“file:///android_asset/”并且包含项目 Assets 目录的内容。
得到这个链接,它对我有用!!...
http://blog.yetisoftware.com/2009/04/02/android-netbeans-and-the-assets-directory/
关于android - 无法访问 Android Assets (并且没有适合我的帖子或教程),请帮忙!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4734928/