我有一个简单的读取 txt 文件的功能。
AssetManager mngr = getAssets();
InputStream is = mngr.open("textdb.txt");
它适用于我的主要 Activity 。但是如果我在单独的类中使用相同的代码,getAssets() 只会返回 null/crash。
我无法找到为什么它只适用于主类。
有什么想法吗?
解决方案:
subClass.ReadSettings(getApplicationContext());
public String[] ReadSettings(Context myContext) {
}
最佳答案
你的其他类也是 Activity
吗?
getAssets() 是 Context 的一个方法。如果您的类不是 Activity,则需要将上下文传递给它,然后对其调用 getAssets。
像这样:
public myClass(Context myContext) {
AssetManager mngr = myContext.getAssets();
InputStream is = mngr.open("textdb.txt");
}
关于android - 获取 Assets ();从另一个类(class),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8458433/