getAssets();从另一个类 [英] getAssets(); from another class

查看:249
本文介绍了getAssets();从另一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

任何想法?

解决方法:

  subClass.ReadSettings(getApplicationContext());

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

解决方案

是其他类也是一个活动? 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");
}

这篇关于getAssets();从另一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆