33

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) {
}
Stecya
  • 22,896
  • 10
  • 72
  • 102
jonassvensson
  • 491
  • 1
  • 6
  • 11

1 Answers1

70

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");
}
Sander van't Veer
  • 5,930
  • 5
  • 35
  • 50
  • 4
    No problem! Could you select his answer as the correct answer by clicking the check mark? This deletes the question from the `Unanswered` list and makes it easier for others with the same problem to find a correct answer. – Sander van't Veer Dec 10 '11 at 19:57