File not found when loading from assets?
Solution 1
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.
Solution 2
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
AJJ
Updated on June 14, 2022Comments
-
AJJ almost 2 years
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 aString
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. -
AJJ almost 8 yearsThe cases/names are exactly the same
-
stormont over 7 yearsI just spent 45 minutes chasing this same problem, with different naming combinations and digging into permissions for the assets/ folder... All it took was an Android Studio restart. Looks like asset changes require a full rebuild from
Build -> Rebuild Project
. -
Sandor Mezil almost 6 yearsAs above, wasted lot of time, in my case because I was placing the folder under
src/main/res
(together with layouts, drawables, ...), and not undersrc/main
as it has to be. -
Phong Nguyen over 4 yearsre-create the file on assets make it work for me (haven't tried to restart Android studio yet), and we can use mContext.assets.list("path") to list out all loaded files
-
sergiu reznicencu over 4 yearsIf restarting the editor doesn't work, try restarting windows. If this doesn't help try switching houses. In the end restart the universe. We may never know where were the hidden bugs lurking.
-
Brian Reinhold over 2 yearsDIdn't work for me. Working in one project, but not another. Can't see what's wrong.