getAssets();从另一个类getAssets

2023-09-05 06:27:39 作者:追尾的猫

我有一个简单的读取一个txt文件的功能。

  AssetManager mngr = getAssets();
InputStream的是= mngr.open(textdb.txt);
 

它可以从我的主要活动。但是,如果我用同样的code在一个单独的类,getAssets()刚刚返回null /崩溃。

我无法找到它为什么只能从主类的工作。

任何想法?

解决方法:

  subClass.ReadSettings(getApplicationContext());

公众的String [] ReadSettings(上下文myContext){
}
 

解决方案 android java获取string.xml android获取string.xml的值

是其他类也是一个活动? getAssets()是背景信息的方法。如果你的类不是一个活动,你需要传递一个上下文到它,然后调用getAssets这一点。

像这样:

 公共MyClass的(语境myContext){
    AssetManager mngr = myContext.getAssets();
    InputStream的是= mngr.open(textdb.txt);
}
 

I have a simple read a txt-file function.

AssetManager mngr = getAssets();
InputStream is = mngr.open("textdb.txt");

It works from my main activity. But if I use the same code in a separate class, getAssets() just return null / crash.

I am unable to find why it only works from the main class.

Any ideas?

Solution:

subClass.ReadSettings(getApplicationContext());

public String[] ReadSettings(Context myContext) {
}

解决方案

Is your other class also an Activity? getAssets() is a method of Context. If your class is not an activity, you'll need to pass a context into it and then call getAssets on that.

Like so:

public myClass(Context myContext) {
    AssetManager mngr = myContext.getAssets();
    InputStream is = mngr.open("textdb.txt");
}

相关推荐