Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

android - getAssets(); from another class

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) {
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...