Reputation: 243
I am trying to compress the bitmap into a jpg in my code. I get a nullpointer exception, Please advice
new Thread(new Runnable() {
@Override
public void run() {
Cursor imageCursor=getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,new String[]{MediaStore.Video.Media.DATA},MediaStore.Video.Media.DISPLAY_NAME+"=?" ,new String[]{imageTitle},null);
imageCursor.moveToFirst();
final String imageData=imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Video.Media.DATA));
dbConnection connection=new dbConnection(getApplicationContext());
SQLiteDatabase db=connection.getWritableDatabase();
File imageFile=new File(imageData);
File outputFile=new File("mnt/sdcard/Images/hiddenImage.jpg");
InputStream is;
try
{
is = new FileInputStream(imageFile);
InputStreamReader inputreader=new InputStreamReader(is);
BufferedReader buffReader=new BufferedReader(inputreader);
final ByteArrayBuffer buffer=new ByteArrayBuffer(512);
int i;
while((i=buffReader.read())!=-1)
{
buffer.append(i);
}
Bitmap imagefile=BitmapFactory.decodeByteArray(buffer.toByteArray(), 0, buffer.toByteArray().length);
OutputStream os=new FileOutputStream("mnt/sdcard/Images/testing.jpg");
imagefile.compress(Bitmap.CompressFormat.JPEG, 100, os);
os.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}).start();
Here is the stack trace:
07-09 14:57:48.595: ERROR/AndroidRuntime(5761): FATAL EXCEPTION: Thread-9
07-09 14:57:48.595: ERROR/AndroidRuntime(5761): java.lang.NullPointerException
07-09 14:57:48.595: ERROR/AndroidRuntime(5761): at com.messageHider.viewImageThumb$1$1.run(viewImageThumb.java:106)
07-09 14:57:48.595: ERROR/AndroidRuntime(5761): at java.lang.Thread.run(Thread.java:1096)
The exception is thrown where I am trying to compress the bitmap: //::imagefile.compress(Bitmap.CompressFormat.JPEG, 100, os);
Upvotes: 0
Views: 2324
Reputation: 1007554
If you have a NullPointerException
in imagefile.compress(Bitmap.CompressFormat.JPEG, 100, os);
, then imagefile
must be null
. This would occur if BitmapFactory
cannot decode the image.
Also:
Your file-reading algorithm is very inefficient. Please consider reading more than one byte at a time. Or, better still, use decodeStream()
rather than decodeByteArray()
on BitmapFactory
.
Make sure you have the WRITE_EXTERNAL_STORAGE
permission.
Never hardwire paths, particularly wrong ones, as you are doing here. Use Environment.getExternalStorageDirectory()
to get at the root of external storage, then use the appropriate File
constructor to assemble a File
object pointing to whatever file you want within that directory.
You do nothing to ensure that the Images/
directory actually exists.
Upvotes: 2