android: nullpointer when saving images
I'm trying to take an image, optimize it as a 65% jpeg and save it to the phones storage. The code below is working fine for me on my nexus one, but is returning a null pointer exception on the last line.
Any idea what I'm doing wrong? Thanks
// image passed in from camera
Bitmap bm = BitmapFactory.decodeFile(selectedImagePath, opts);
// create output
FileOutputStream fileOutputStream = null;
// create filename & directory
String nameFile = "ms" + String.valueOf(System.currentTimeMillis())+ ".jpg";
String directory = "/DCIM/MySeats/";
// try creating the directories if they don't already exist
File file = new File(Environment.getExternalStorageDirectory(),directory);
file.mkdirs();
// prep output
fileOutputStream = new FileOutputStream(Environment.getExternalStorageDirectory().toString()+ directory + nameFile);
optimizedImagePath = Environment.getExternalStorageDirectory().toString()+ directory + nameFile;
// write file through a buffered stream
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
// This line causes a null pointer exception on some phones?
开发者_运维百科// What am I missing?
bm.compress(CompressFormat.JPEG, 65, bos);
Null pointer exception in the last line is due to the two variable that is used in the last line is null
check for bm != null check for bos!= null
I am going to assume you are launching the native camera application and this code is all probably from the onActivityResult() method.
Your problem could be that a couple of phones with the carrier specific builds disregard the MediaStore.EXTRA_OUTPUT
parameter and just return the image in the returned Intent
. This would mean the image at the path you expect is null and you have to extract the image from the intent using getData()
sometimes.
精彩评论