Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getAssets(); from another class

Tags:

android

assets

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) {
}
like image 713
jonassvensson Avatar asked Dec 10 '11 17:12

jonassvensson


1 Answers

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");
}
like image 143
Sander van't Veer Avatar answered Nov 14 '22 02:11

Sander van't Veer