AJJ
AJJ

Reputation: 2074

File not found when loading from assets?

I included several pre-made .png files in my assets folder, but only some of them are getting through without error:

AssetManager assetManager = context.getAssets();
Inputstream in = assetManager.open(assetName);

where assetName is a String containing something like "myPic.png".

It seems to work for some of the files, but for others it throws java.io.FileNotFoundException: myPic.png even though I see it right there in the Assets folder alongside plenty of other files that seem to be making the cut.

Upvotes: 12

Views: 18110

Answers (3)

Hamy
Hamy

Reputation: 21542

If you are running into this during an Android Instrumentation Test, the issue can be fixed by changing this:

ApplicationProvider.getApplicationContext().getAssets().open(YOUR_FILE)

to this:

InputStream inputStream = InstrumentationRegistry.getInstrumentation().
     getContext().getAssets().open(YOUR_FILE);

The application provider knows to redirect resource requests to your instrumentation resources and then fallback to the application under test, but it does not have the same intelligence for assets

Upvotes: 4

AJJ
AJJ

Reputation: 2074

Apparently closing / reopening the project in Android Studio was enough to get it to work correctly. No idea why it wasn't noticing all the assets in the first place, but now it does after restarting.

Upvotes: 11

Angel Moreira
Angel Moreira

Reputation: 62

Make sure that the names of your variables correspond to the name of your files, they are case sensitive. That could be why some file are not being read.

Upvotes: 0

Related Questions