11

Saving the file:

FileOutputStream fo = null; 
try { 
        fo = this.openFileOutput("test.png", Context.MODE_WORLD_READABLE); 
} catch (FileNotFoundException e) { 
        e.printStackTrace(); 
} 
bitmap.compress(CompressFormat.PNG, 100, fo)

Loading the file:

String fname = this.getFilesDir().getAbsolutePath()+"/test.png"; 
Bitmap bMap = BitmapFactory.decodeFile(fname);
i.setImageBitmap(bMap);

The last line gives a null pointer exception, why is BitmapFactory.decodeFile returning null? I can verify that the file is getting saved correctly as I can pull it using adb and see the png displaying properly.

einverne
  • 6,454
  • 6
  • 45
  • 91
stealthcopter
  • 13,964
  • 13
  • 65
  • 83

2 Answers2

20

If the NullPointerException is directly on this line:

i.setImageBitmap(bMap);

Then your problem is that i is null. Given that you're calling setImageBitmap(), I am guessing that i is an ImageView -- make sure your findViewById() call is working.

Also, you should use the following to get fname:

String fname=new File(getFilesDir(), "test.png").getAbsolutePath();

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
2

When using the options parameter in the DecodeFile method be sure that the InJustDecodeBounds property is set to false or otherwise it will always return null. This can be set to true when you just want the file to be decoded but you don't need it further in your app/code. This way no extra memory needs to be allocated. See here for an example.

Jeroen VL
  • 341
  • 5
  • 9