Kotlin Read Image Files in Storage (KRIFS)

I am quite new to Android. I want to save an image to internal memory and then take the image from internal memory and load it into the image view. I have successfully saved the image to internal memory using the following code.

void  saveImage () {
    String fileName= "image.jpg" ;
     //File file=new File(fileName); 
    try 
    {

       FileOutputStream fOut=openFileOutput(fileName, MODE_PRIVATE);
       bmImg.compress(Bitmap.CompressFormat.JPEG, 100 , fOut);

    }
    catch (Exception e)
    {
       e.printStackTrace();
    }
}

But when I try to fetch the image to load in the ImageView component I get an error like the following.

Null pointer exception

Solution

It happens because your byte array has no value (null), please create an instance of it, and set its size, here is an example.

FileInputStream fin = null ;

    ImageView img= new ImageView( this );
     try {
        fin = openFileInput( "image.jpg" );
         if (fin != null && fin.available() > 0 ) {
            Bitmap bmp=BitmapFactory.decodeStream(fin)
            img.setImageBitmap(bmp);
         } else {
             //input stream has not much data to convert into Bitmap
          }
    } catch (FileNotFoundException e) {
         // TODO Auto-generated catch block
        e.printStackTrace();
    }

Post a Comment

Previous Next

نموذج الاتصال