-3

I have already seen many questions in stackoverflow but none of them able to solve my problem. Here is my code.There is no error in code but app is crashing at runtime giving this error in Logcat - Attempt to invoke virtual method 'android.graphics.Bitmap android.graphics.drawable.BitmapDrawable.getBitmap()' on a null object reference

public void SaveImageInFirebase(){
        FirebaseStorage storage = FirebaseStorage.getInstance();
        StorageReference storageRef = storage.getReferenceFromUrl("gs://opiniondonkey-9c20e.appspot.com");
        SimpleDateFormat df = new SimpleDateFormat("ddMMyyHHmmss");
        Date dataobj = new Date();
        String imagePath = df.format(dataobj) + ".jpg";
        StorageReference ImageRef = storageRef.child("images/" + imagePath);

        mPic.setDrawingCacheEnabled(true);
        mPic.buildDrawingCache();
        Drawable drawable = mPic.getDrawable();
        //TODO:: error in below line.
        Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG,100, baos);
        byte[] data = baos.toByteArray();
        UploadTask uploadTask = ImageRef.putBytes(data);
        uploadTask.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(getApplicationContext(),"Welcome To Opinion Donkey",Toast.LENGTH_LONG).show();
            }
        }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                Task<Uri> downloadUrl = taskSnapshot.getStorage().getDownloadUrl();
                myRef.child("Users").child(name).child("ProfileUrl").setValue(downloadUrl);
            }
        });

    }

I want when someone logins again then google id picture should not overrides over my user picture.

Ayush Khanna
  • 176
  • 12

1 Answers1

1

May be mPic.getDrawable(); is returning null. so drawable is null and you are accessing it by ((BitmapDrawable)drawable).getBitmap();

It might be because Picasso loads image in ImageView async and you are trying to access that before it is loaded/downloaded.

so mPic.getDrawable() returns null.

Add check before accessing if(drawable != null) there.

Also, this needs to be called only after Picasso done with it's loading. so you can add listener there and access image only after it is done loading.

Jay Patel
  • 486
  • 1
  • 4
  • 14