StorageReference error when uploading images to Firebase [duplicate]

问题: This question already has an answer here: What is a NullPointerException, and how do I fix it? 12 answers I'm going through a small mistake that I...

问题:

This question already has an answer here:

I'm going through a small mistake that I can not solve, I need to do the next action. When the user touches the image to take a photo, the camera must be opened, when the user wants to load the image taken, pressing the button must send that photo stored in the Firebase Storage, when I perform this action my app leaves to work and it generates the following error :

Error java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.storage.UploadTask com.google.firebase.storage.StorageReference.putBytes(byte[])' on a null object reference

My code :

public class VerifyIDActivity extends AppCompatActivity {


    /** BITMAP DE LA FOTO TOMADA **/
    Bitmap imageBitmap;

    /**Codigo para pedir la captura de imagen*/
    private static final int REQUEST_IMAGE_CAPTURE = 111;

    Button btVerifyID;
    //EditText etVerifyCurp;
    ImageView imgID;
    CircleImageView imgSelfie;
   // TextInputLayout tiVerifyCurp;


    /**FIREBASE REFERENCES STORAGE**/
    // Create a storage reference from our app
   // StorageReference storageRef;
    // Create a reference to verified Users photos
    StorageReference verifiedUsersRef;

    FirebaseAuth firebaseAuth;
    StorageReference firebaseStorage;

    /**Uid del usuario que se esta verificando*/
    String currentUserUid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_verify_id);

        /** ESTABLECER PORTRAIT SIN QUE SE PUEDA PONER EN LANDSCAPE**/
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        Intent i = getIntent();
        final String completeName = i.getStringExtra("completeName");

        btVerifyID = findViewById(R.id.btVerifyID);
       // etVerifyCurp = findViewById(R.id.etVerifyCurp);
        //imgID = findViewById(R.id.imgID);
        imgSelfie = findViewById(R.id.imgSelfie);
       // tiVerifyCurp = findViewById(R.id.tiVerifyCurp);


        //tiVerifyCurp.setError("18 Caracteres");

        firebaseAuth = FirebaseAuth.getInstance();
        FirebaseUser user = firebaseAuth.getCurrentUser();
        firebaseStorage = FirebaseStorage.getInstance().getReference();

        if (user != null) {
            String currentUserUid = firebaseAuth.getCurrentUser().getUid();

            verifiedUsersRef = firebaseStorage.child("verified_user_photos/" + currentUserUid);
        }

        imgSelfie.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Build.VERSION.SDK_INT >= 23) {
                    //do your check here

                    // Here, thisActivity is the current activity
                    if (ContextCompat.checkSelfPermission(VerifyIDActivity.this,
                            android.Manifest.permission.CAMERA)
                            != PackageManager.PERMISSION_GRANTED) {

                        // Should we show an explanation?
                        if (ActivityCompat.shouldShowRequestPermissionRationale(VerifyIDActivity.this,
                                android.Manifest.permission.CAMERA)) {

                            // Show an explanation to the user *asynchronously* -- don't block
                            // this thread waiting for the user's response! After the user
                            // sees the explanation, try again to request the permission.

                            ActivityCompat.requestPermissions(VerifyIDActivity.this,
                                    new String[]{android.Manifest.permission.CAMERA},
                                    REQUEST_IMAGE_CAPTURE);

                            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            if (takePictureIntent.resolveActivity(VerifyIDActivity.this.getPackageManager()) != null) {
                                startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
                            }

                        } else {

                            // No explanation needed, we can request the permission.

                            ActivityCompat.requestPermissions(VerifyIDActivity.this,
                                    new String[]{android.Manifest.permission.CAMERA},
                                    REQUEST_IMAGE_CAPTURE);

                            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            if (takePictureIntent.resolveActivity(VerifyIDActivity.this.getPackageManager()) != null) {
                                startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
                            }

                            // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
                            // app-defined int constant. The callback method gets the
                            // result of the request.


                        }
                    } else {
                        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        if (takePictureIntent.resolveActivity(VerifyIDActivity.this.getPackageManager()) != null) {
                            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
                        }
                    }
                }else {

                    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    if (takePictureIntent.resolveActivity(VerifyIDActivity.this.getPackageManager()) != null) {
                        startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
                    }
                }

            }
        });

        /**
        imgID.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Build.VERSION.SDK_INT >= 23) {
                    //do your check here

                    // Here, thisActivity is the current activity
                    if (ContextCompat.checkSelfPermission(VerifyIDActivity.this,
                            android.Manifest.permission.CAMERA)
                            != PackageManager.PERMISSION_GRANTED) {

                        // Should we show an explanation?
                        if (ActivityCompat.shouldShowRequestPermissionRationale(VerifyIDActivity.this,
                                android.Manifest.permission.CAMERA)) {

                            // Show an explanation to the user *asynchronously* -- don't block
                            // this thread waiting for the user's response! After the user
                            // sees the explanation, try again to request the permission.

                            ActivityCompat.requestPermissions(VerifyIDActivity.this,
                                    new String[]{android.Manifest.permission.CAMERA},
                                    REQUEST_IMAGE_CAPTURE);

                            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            if (takePictureIntent.resolveActivity(VerifyIDActivity.this.getPackageManager()) != null) {
                                startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
                            }

                        } else {

                            // No explanation needed, we can request the permission.

                            ActivityCompat.requestPermissions(VerifyIDActivity.this,
                                    new String[]{android.Manifest.permission.CAMERA},
                                    REQUEST_IMAGE_CAPTURE);

                            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            if (takePictureIntent.resolveActivity(VerifyIDActivity.this.getPackageManager()) != null) {
                                startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
                            }

                            // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
                            // app-defined int constant. The callback method gets the
                            // result of the request.


                        }
                    } else {
                        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        if (takePictureIntent.resolveActivity(VerifyIDActivity.this.getPackageManager()) != null) {
                            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
                        }
                    }
                }else {

                    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    if (takePictureIntent.resolveActivity(VerifyIDActivity.this.getPackageManager()) != null) {
                        startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
                    }
                }




            }

        });**/


        btVerifyID.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                String photoUrl = "verified_user_photos/" + currentUserUid + ".png";

                if (imageBitmap != null) {

                    encodeBitmapAndSaveToFirebase(imageBitmap);

                    Intent i = new Intent(VerifyIDActivity.this, VerifyWhatsActivity.class);
                    i.putExtra("completeName", completeName);
                    i.putExtra("photoUrl", photoUrl);
                    startActivity(i);
                    finish();
                }else {
                    error("Por favor sube una foto de tu identificacion.");
                }

            }
        });
    }



    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_IMAGE_CAPTURE: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.
                    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    if (takePictureIntent.resolveActivity(VerifyIDActivity.this.getPackageManager()) != null) {
                        startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
                    }

                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == FinalMatchActivity2.RESULT_OK) {
            Bundle extras = data.getExtras();
            imageBitmap = (Bitmap) extras.get("data");

            imgSelfie.setImageBitmap(imageBitmap);
            //imgID.setImageBitmap(imageBitmap);


        }
    }



    public void encodeBitmapAndSaveToFirebase(Bitmap bitmap) {



        // Get the data from an ImageView as bytes
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] data = baos.toByteArray();

        UploadTask uploadTask = verifiedUsersRef.putBytes(data);

        uploadTask.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception exception) {
                // Handle unsuccessful uploads
            }
        }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                // taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
                //Uri downloadUrl = taskSnapshot.getDownloadUrl();

                // Toast.makeText(FinalMatchActivity.this, "Sucess", Toast.LENGTH_SHORT).show();

                NotificationCompat.Builder mBuilder;
                NotificationManager mNotifyMgr =(NotificationManager) getApplicationContext().getSystemService(NOTIFICATION_SERVICE);

                int icono = R.drawable.qapplalog;
                Intent i = new Intent(VerifyIDActivity.this, MainActivity.class);
                PendingIntent pendingIntent = PendingIntent.getActivity(VerifyIDActivity.this, 0, i, 0);

                mBuilder =new NotificationCompat.Builder(getApplicationContext())
                        .setContentIntent(pendingIntent)
                        .setSmallIcon(icono)
                        .setContentTitle("Foto subida")
                        .setContentText("Subida correctamente")
                        .setVibrate(new long[] {100, 250, 100, 500})
                        .setAutoCancel(true);



                mNotifyMgr.notify(1, mBuilder.build());

            }
        });
    }


    AlertDialog alert = null;

    private void error(String error){
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(error)
                .setCancelable(false)
                .setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                    }
                });

        alert = builder.create();
        alert.show();
    }
}

What you hope to achieve is to be able to send and store that image, without any problem.


回答1:

verifiedUsersRef is null. You probably never assigned it.

  • 发表于 2019-07-07 17:30
  • 阅读 ( 233 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除