我试图从另一个类文件访问我的应用程序的资产。很显然this.getAssets()
不起作用,所以我尝试将上下文作为参数传递给类。我使用了各种各样的'上下文' - getBaseContext()
,getApplicationContext()
,但是它们全都导致NullPointerException
。Android - 从另一个类访问资产不起作用
这里是我使用的代码。它在Activity中运行良好,但我无法弄清楚如何使它在外部类中工作。
private String pickText(){
String line = null;
try {
AssetManager am = this.getAssets();
InputStream fstream = am.open("plan.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
line = br.readLine();
for(int i = 1; i < id && line != null; i++){
line = br.readLine();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return line;
}
任何想法? 谢谢。
你在哪里调用pickText()方法?如果在活动中,然后传递上下文 –
我有很多不同的活动,所有访问资产只需使用“getAssets”。也许你的班级需要扩展“活动”。 – HpTerm
对不起,应该更清楚 - 第二课不是活动。这是一个对象。 –