I'm trying to select a picture from gallery , get bitmap of that picture and encode that bitmap into base64. But I get this error:
Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
Here is what I've done :
private Bitmap bitmap;
private String encodedbitmap;
...
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 100);
...
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==100 && resultCode==RESULT_OK ){
Uri selectedimg=data.getData();
new Encodeimg().execute();
}
...
private class Encodeimg extends AsyncTask<Void,Void,Void>{
@Override
protected Void doInBackground(Void... params) {
bitmap=BitmapFactory.decodeFile(selectedimg.getPath());
ByteArrayOutputStream stream= new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream);
byte[] bytes=stream.toByteArray();
encodedbitmap= Base64.encodeToString(bytes,0);
return null;
}
EDIT: I know what a NullPointerException is. I just don't understand why I get that error in this situation. Because I don't see a null object here.