File not found when loading from assets?

12,785

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

Share:
12,785
AJJ
Author by

AJJ

Updated on June 14, 2022

Comments

  • AJJ
    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 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.

  • AJJ
    AJJ almost 8 years
    The cases/names are exactly the same
  • stormont
    stormont over 7 years
    I 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
    Sandor Mezil almost 6 years
    As above, wasted lot of time, in my case because I was placing the folder under src/main/res (together with layouts, drawables, ...), and not under src/main as it has to be.
  • Phong Nguyen
    Phong Nguyen over 4 years
    re-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
    sergiu reznicencu over 4 years
    If 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
    Brian Reinhold over 2 years
    DIdn't work for me. Working in one project, but not another. Can't see what's wrong.