我遇到一个我无法解决的小错误,我需要执行下一步操作。当用户触摸图像进行拍照时,必须打开相机,当用户要加载拍摄的图像时,按下按钮必须发送存储在Firebase Storage
中的照片,当我执行此操作时,我的应用程序离开工作,并产生以下错误:
错误 java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'com.google.firebase.storage.UploadTask com.google.firebase.storage.StorageReference.putBytes(byte [])'
我的代码:
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();
}
}
您希望实现的目标是能够毫无问题地发送和存储该图像。
答案 0 :(得分:0)
verifiedUsersRef
为空。您可能从未分配过它。