Null-pointer issue displaying an image from assets folder Android 2.2 SDK

后端 未结 2 340
耶瑟儿~
耶瑟儿~ 2021-01-28 13:34

I looked at the 2 examples on Stack, but can\'t get them to work. I\'m simply trying to grab an image from a folder in assets and set it as in ImageView, but get a null pointer

相关标签:
2条回答
  • 2021-01-28 14:25

    Where is "file:///android_asset/Samples/" + imageName coming from? If your hierarchy looks like assets/file_name.jpg, you would just call open(file_name.jpg). In other words, try replacing your file:///android_asset/Samples/" + imageName with just imageName.

    Check out the API Demos, specifically the ReadAsset.java class:

    try {
            InputStream is = getAssets().open("read_asset.txt");
    

    ...

    where the assets folder looks like

    alt text

    0 讨论(0)
  • 2021-01-28 14:31

    Frank I had the same problem !

    I had my PNG images within "assets" of my project and AssetManager.open() kept on giving me an exception because it couldn't find the file !

    I investigated by using assetManager.list("") to list what's in "assets". I subsequently discovered that my images were actually NOT added to the "assets" !

    As you can imagine I was getting pretty pissed off at this point because obviously my images should have been within assets because I could see them play as day in Eclipse within the damn "assets" folder of my project.

    Solution

    1. back-up the files that are in assets folder of your project. I used Windows Explorer for this drag-drop operation.
    2. go back to eclipse and delete your files within "assets". Use Eclipse for this so that you don't need to refresh your project.
    3. get your Windows Explorer window back and drag your backed-up files into Eclipse and onto "assets". Your cursor changes to a "+". When you let go of your mouse button Eclipse will prompt you if you want to link or copy. Select copy.
    4. rebuild your project and the images are now truly in assets.

    Bonus - I updated your getBitmapFromAsset() method:

    private Bitmap getBitmapFromAsset(String strName) throws IOException
    {
        AssetManager assetManager = getAssets();
    
        InputStream istr = assetManager.open(strName);
        Bitmap bitmap = BitmapFactory.decodeStream(istr);
    
        return bitmap;
    }
    
    0 讨论(0)
提交回复
热议问题