niklassc
niklassc

Reputation: 550

Error when using AssetManager to open assets file

I am trying to open an assets file in my Android app. When I try to use the following code to do that I get the error message Cannot resolve method 'getBaseContext()'. First I tried to do it with just getAssets() instead of getBaseContext().getAssets() which displayed the error message Cannot resolve method 'getAssets()'. I also tried to clean and rebuild the project but it did not change anything. What am I doing wrong?

try {
    AssetManager assetManager = getBaseContext().getAssets();
    InputStream is = assetManager.open("MAIN.sql");
} catch (IOException e) {
    e.printStackTrace();
}

Upvotes: 0

Views: 1509

Answers (1)

Ariane Breton
Ariane Breton

Reputation: 1333

Instead of getBaseContext() , try creating a class level variable Context at the top like this:

Context mContext = YourActivityName.this;

and then use this variable to get the assets

mContext.getAssets();

If you are trying to do this on a NON Activity class, like a class you created separately not relating any activity you will have to receive the activity context as a parameter so when you instance your class you send the context like this

YourAssetClass assetClass = new YourAssetClass(mContext)
assetClass.getAssets();

Hope it helps.

Upvotes: 2

Related Questions