Sudharshan Venkatesh Sudharshan Venkatesh - 1 year ago 70
Android Question

Null Pointer Exception when trying to compress Bitmap

I'm getting a null pointer exception when trying to compress a bitmap so I can send it to a ByteArrayOutputStream to get a byte array. I need this byte array so I can upload the image to my Parse database as a ParseFile. The log error is shown below.

01-11 23:29:41.522 32015-32015/com.example.whhsfbla.fashionnow E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.whhsfbla.fashionnow, PID: 32015
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean$CompressFormat, int,' on a null object reference
at com.example.whhsfbla.fashionnow.PostActivity.uploadPost(
at com.example.whhsfbla.fashionnow.PostActivity.access$100(
at com.example.whhsfbla.fashionnow.PostActivity$2.onClick(
at android.view.View.performClick(
at android.view.View$
at android.os.Handler.handleCallback(
at android.os.Handler.dispatchMessage(
at android.os.Looper.loop(
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(

The line which causes the error is
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);

public class PostActivity extends Activity {

private final int SELECT_PHOTO = 1;
private InputStream imageStream;
private Uri uploadFileUri;
private Bitmap bitmap;
private TextView txtPostTitle;
private EditText editText;
private Button btnChoosePic, btnUploadPost;
private ImageView imgPreview;

protected void onCreate(Bundle savedInstanceState) {

txtPostTitle = (TextView) findViewById(;
editText = (EditText) findViewById(;
btnChoosePic = (Button) findViewById(;
btnUploadPost = (Button) findViewById(;
imgPreview = (ImageView) findViewById(;

btnChoosePic.setText("Choose Picture");
btnUploadPost.setText("Create Post");

/*btnChoosePic.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
} catch (IOException e) {
}); */

btnChoosePic.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
} catch (IOException e) {

btnUploadPost.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {


private void openImageIntent() throws IOException {
final File root = new File(Environment.getExternalStorageDirectory() +
File.separator + "MyDir" + File.separator);
final String fileName = File.createTempFile("tmp", ".txt").getPath();
final File sdImageMainDirectory = new File(root, fileName);

uploadFileUri = Uri.fromFile(sdImageMainDirectory);

final List<Intent> cameraIntents = new ArrayList<Intent>();
final Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
final PackageManager packageManager = getPackageManager();
final List<ResolveInfo> resolveInfoList = packageManager.queryIntentActivities(captureIntent, 0);
for (ResolveInfo res : resolveInfoList) {
final String packageName = res.activityInfo.packageName;
final Intent intent = new Intent(captureIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName,;
intent.putExtra(MediaStore.EXTRA_OUTPUT, uploadFileUri);

final Intent galleryIntent = new Intent();

final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");

chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[cameraIntents.size()]));

startActivityForResult(chooserIntent, SELECT_PHOTO);

private void uploadPost() {
// Locate the image in res > drawable-hdpi
bitmap = BitmapFactory.decodeResource(getResources(),;
// Convert it to byte
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Compress image to lower quality scale 1 - 100
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] image = stream.toByteArray();

// Create the ParseFile
ParseFile file = new ParseFile("image.png",image);
// Upload the image into ParseCloud

// Create a New Class called "ImageUpload" in Parse
ParseObject post = new ParseObject("Post");

// Create a column named "ImageName" and set the string
post.put("title", editText.getText().toString());

// Create a column named "ImageFile" and insert the image
post.put("ImageFile", file);

post.put("user", User.username);

// Create the class and the columns

// Show a simple toast message
Toast.makeText(PostActivity.this, "Post Uploaded",


protected void onActivityResult(int requestCode, int resultCode, Intent imageIntent) {
super.onActivityResult(requestCode, resultCode, imageIntent);

if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PHOTO) {
//Get the URI
final boolean isCamera;
if (imageIntent == null) {
isCamera = true;
} else {
final String action = imageIntent.getAction();
if (action == null) {
isCamera = false;
} else {
isCamera = action.equals(MediaStore.ACTION_IMAGE_CAPTURE);


Uri selectedImageUri;
if (isCamera) {
selectedImageUri = uploadFileUri;
} else {
selectedImageUri = imageIntent == null ? null : imageIntent.getData();

//Get the Bitmap from the URI, and set it to the ImageView
try {
imageStream = getContentResolver().openInputStream(selectedImageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
} catch (FileNotFoundException e) {

Answer Source

You're getting a null pointer exception because bitmap is null. Replace the line that goes

bitmap = BitmapFactory.decodeResource(getResources(),;

with this

bitmap = ((BitmapDrawable) imgPreview.getDrawable()).getBitmap();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download