Estoy intentando subir una imagen a Firebase Cloud Storage pero cuando presiono el botón "Subir Imagen"la aplicación se detiene. Cabe mencionar que tengo otra activity con el mismo código y funciona con normalidad. Sin embargo, al replicarlo en otra activity no funciona.
He revisado el Logcat y visualizo el siguiente mensaje:
2020-06-03 15:23:29.304 23377-23450/com.example.barbercut E/StorageException: StorageException has occurred.
Object does not exist at location.
Code: -13010 HttpResult: 404
2020-06-03 15:23:29.307 23377-23450/com.example.barbercut E/StorageException: { "error": { "code": 404, "message": "Not Found. Could not get object", "status": "GET_OBJECT" }}
java.io.IOException: { "error": { "code": 404, "message": "Not Found. Could not get object", "status": "GET_OBJECT" }}
at com.google.firebase.storage.network.NetworkRequest.parseResponse(com.google.firebase:firebase-storage@@19.1.1:433)
at com.google.firebase.storage.network.NetworkRequest.parseErrorResponse(com.google.firebase:firebase-storage@@19.1.1:450)
at com.google.firebase.storage.network.NetworkRequest.processResponseStream(com.google.firebase:firebase-storage@@19.1.1:441)
at com.google.firebase.storage.network.NetworkRequest.performRequest(com.google.firebase:firebase-storage@@19.1.1:272)
at com.google.firebase.storage.network.NetworkRequest.performRequest(com.google.firebase:firebase-storage@@19.1.1:286)
at com.google.firebase.storage.internal.ExponentialBackoffSender.sendWithExponentialBackoff(com.google.firebase:firebase-storage@@19.1.1:70)
at com.google.firebase.storage.internal.ExponentialBackoffSender.sendWithExponentialBackoff(com.google.firebase:firebase-storage@@19.1.1:62)
at com.google.firebase.storage.GetDownloadUrlTask.run(com.google.firebase:firebase-storage@@19.1.1:76)
at java.util.concurrent.ThreadPoolExecutor.processTask(ThreadPoolExecutor.java:1187)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1152)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:784)
2020-06-03 15:23:29.387 616-797/? E/BufferQueueProducer: [] mConsumerName == NULL!!!!!!
public class fotodni extends AppCompatActivity {
private static final int RC_GALERY = 123;
private static final int RC_CAMERA = 124;
private static final int RP_CAMERA = 125;
private static final int RP_STORAGE = 126;
private static final String IMAGE_DIRECTORY = "/MyPhotoApp";
private static final String MY_DNI = "my_dni";
private static final String PATH_DOCUMENTOS = "documentos";
private static final String PATH_DNI = "DNI";
private static final String PHOTO_DNI = "Foto_Dni";
@BindView(R.id.container)
ConstraintLayout container;
@BindView(R.id.progressBar)
ProgressBar progressBar;
private String mCurrentPhotoPath;
private Uri mPhotoSelectedUri;
private Button pasaPenales;
private ImageView photoProfile;
private Button upPhoto, selectPhoto, capturePhoto;
private ImageButton closePhoto;
private TextView mTvMessage;
private StorageReference mStorageReference;
private DatabaseReference mDatabaseReference;
private FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
private DatabaseReference mDataBase2;
private BarberProvider mBarberProvider;
private AuthProviders mAuthProvider;
private TextView nameProfile;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_fotodni);
nameProfile=findViewById (R.id.dniProfile);
mBarberProvider = new BarberProvider ();
mAuthProvider =new AuthProviders ();
mFirebaseAuth=FirebaseAuth.getInstance ();
mDataBase2= FirebaseDatabase.getInstance ().getReference ();
myToolbar.show (this, "Foto DNI", true);
pasaPenales = findViewById (R.id.btnDNI2);
pasaPenales.setOnClickListener (new View.OnClickListener () {
@Override
public void onClick(View v) {
goToSelectAuth5 ();
}
});
photoProfile = findViewById (R.id.photoDNI1);
upPhoto = findViewById (R.id.upPhotoProfile);
selectPhoto = findViewById (R.id.select_Photo);
capturePhoto = findViewById (R.id.capture_Photo);
closePhoto = findViewById (R.id.btnDelete);
mTvMessage = findViewById (R.id.messageLoad);
getClientInfo();
upPhoto.setOnClickListener (new View.OnClickListener () {
@Override
public void onClick(View v) {
loadPhoto ();
}
});
selectPhoto.setOnClickListener (new View.OnClickListener () {
@Override
public void onClick(View v) {
checkPermissionToApp (Manifest.permission.READ_EXTERNAL_STORAGE, RP_STORAGE);
//fromGallery ();
}
});
capturePhoto.setOnClickListener (new View.OnClickListener () {
@Override
public void onClick(View v) {
//captureCamara ();
//dispatchTakePictureIntent();
checkPermissionToApp (Manifest.permission.CAMERA, RP_CAMERA);
}
});
closePhoto.setOnClickListener (new View.OnClickListener () {
@Override
public void onClick(View v) {
closeImage ();
}
});
configFirebase ();
configPhotoProfile ();
}
private void configPhotoProfile() {
mStorageReference.child (PATH_DOCUMENTOS).child (MY_DNI).getDownloadUrl ()
.addOnSuccessListener (new OnSuccessListener<Uri> () {
@Override
public void onSuccess(Uri uri) {
final RequestOptions options = new RequestOptions ()
.centerCrop ()
.diskCacheStrategy (DiskCacheStrategy.RESOURCE);
Glide.with (fotodni.this)
.load (uri)
.apply (options)
.into (photoProfile);
closePhoto.setVisibility (View.VISIBLE);
}
})
.addOnFailureListener (new OnFailureListener () {
@Override
public void onFailure(@NonNull Exception e) {
closePhoto.setVisibility (View.GONE);
Toast.makeText (fotodni.this, "Agregar Otra Imagen", Toast.LENGTH_SHORT).show ();
}
});
}
private void configFirebase() {
mStorageReference = FirebaseStorage.getInstance ().getReference ();
FirebaseDatabase database = FirebaseDatabase.getInstance ();
mDatabaseReference = database.getReference ().child (PATH_DOCUMENTOS).child (PATH_DNI);
}
private void checkPermissionToApp(String permissionStr, int requestPermission) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission (this, permissionStr) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions (this, new String[]{permissionStr}, requestPermission);
return;
}
}
switch (requestPermission) {
case RP_STORAGE:
fromGallery ();
break;
case RP_CAMERA:
dispatchTakePictureIntent ();
break;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
switch (requestCode) {
case RP_STORAGE:
fromGallery ();
break;
case RP_CAMERA:
dispatchTakePictureIntent ();
break;
}
}
super.onRequestPermissionsResult (requestCode, permissions, grantResults);
}
private void captureCamara() {
Intent intent = new Intent (MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult (intent, RC_CAMERA);
}
private void fromGallery() {
Intent intent = new Intent (Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult (intent, RC_GALERY);
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent (MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity (getPackageManager ()) != null) {
File photoFile;
photoFile = createImageFile ();
if (photoFile != null) {
Uri photoUri = FileProvider.getUriForFile (this,
"com.example.barbercut", photoFile);
takePictureIntent.putExtra (MediaStore.EXTRA_OUTPUT, photoUri);
startActivityForResult (takePictureIntent, RC_CAMERA);
}
}
}
private File createImageFile() {
final String timeStamp = new SimpleDateFormat ("dd-MM-yyyy_HHmmss", Locale.ROOT)
.format (new Date ());
final String imageFileName = MY_DNI + timeStamp + "_";
File storageDir = getExternalFilesDir (Environment.DIRECTORY_PICTURES);
File image = null;
try {
image = File.createTempFile (imageFileName, "jpg", storageDir);
mCurrentPhotoPath = image.getAbsolutePath ();
} catch (IOException e) {
e.printStackTrace ();
}
return image;
}
private void closeImage() {
mStorageReference.child (PATH_DOCUMENTOS).child (MY_DNI).delete ().addOnSuccessListener (new OnSuccessListener<Void> () {
@Override
public void onSuccess(Void aVoid) {
mDatabaseReference.removeValue ();
photoProfile.setImageBitmap (null);
closePhoto.setVisibility (View.GONE);
Snackbar.make (container, R.string.main_message_delete_succes, Snackbar.LENGTH_LONG).show ();
}
}).addOnFailureListener (new OnFailureListener () {
@Override
public void onFailure(@NonNull Exception e) {
Snackbar.make (container, R.string.main_message_delete_error, Snackbar.LENGTH_LONG).show ();
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult (requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case RC_GALERY:
if (data != null) {
mPhotoSelectedUri = data.getData ();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap (this.getContentResolver ()
, mPhotoSelectedUri);
photoProfile.setImageBitmap (bitmap);
closePhoto.setVisibility (View.GONE);
mTvMessage.setText (R.string.main_message_question_upload);
} catch (Exception e) {
e.printStackTrace ();
}
}
break;
case RC_CAMERA:
/*Bundle extras = data.getExtras ();
Bitmap bitmap = (Bitmap)extras.get ("data");*/
mPhotoSelectedUri = addPicGallery ();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap (this.getContentResolver ()
, mPhotoSelectedUri);
photoProfile.setImageBitmap (bitmap);
closePhoto.setVisibility (View.GONE);
mTvMessage.setText (R.string.main_message_question_upload);
} catch (IOException e) {
e.printStackTrace ();
}
break;
}
}
}
private Uri addPicGallery() {
Intent mediaScanIntent = new Intent (Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File file = new File (mCurrentPhotoPath);
Uri contentUri = Uri.fromFile (file);
mediaScanIntent.setData (contentUri);
this.sendBroadcast (mediaScanIntent);
mCurrentPhotoPath = null;
return contentUri;
}
public Bitmap getResizedBitmap(Bitmap image, int maxSize) {
int width = image.getWidth();
int height = image.getHeight();
float bitmapRatio = (float)width / (float) height;
if (bitmapRatio > 1) {
width = maxSize;
height = (int) (width / bitmapRatio);
} else {
height = maxSize;
width = (int) (height * bitmapRatio);
}
return Bitmap.createScaledBitmap(image, width, height, true);
}
private void loadPhoto() {
progressBar.setVisibility(View.VISIBLE);
Bitmap bitmap;
try{
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver() , mPhotoSelectedUri);
bitmap = getResizedBitmap(bitmap, 480);
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
StorageReference profileReference = mStorageReference.child(PATH_DOCUMENTOS);
StorageReference photoReference = profileReference.child (PHOTO_DNI).child(mAuthProvider.getId () + ".jpg");
UploadTask uploadTask = photoReference.putBytes(data);
uploadTask
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot> () {
@Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100 * taskSnapshot.getBytesTransferred()) /
taskSnapshot.getTotalByteCount();
progressBar.setProgress((int)progress);
mTvMessage.setText(String.format("%s%%", progress));
}
})
.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot> () {
@Override
public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
progressBar.setVisibility(View.GONE);
}
})
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Snackbar.make(container, R.string.main_message_upload_success, Snackbar.LENGTH_LONG).show();
taskSnapshot.getStorage().getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
String image = uri.toString ();
Barber barber = new Barber ();
barber.setImage (image);
savePhotoUrl2 (uri);
closePhoto.setVisibility(View.VISIBLE);
mTvMessage.setText(R.string.main_message_done);
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Snackbar.make(container, R.string.main_message_upload_error, Snackbar.LENGTH_LONG).show();
}
});
} catch (Exception e){
e.printStackTrace();
}
if (true){
return;
}
StorageReference profileReference = mStorageReference.child (PATH_DOCUMENTOS);
StorageReference photoReference = profileReference.child (MY_DNI);
photoReference.putFile (mPhotoSelectedUri)
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
@Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100 * taskSnapshot.getBytesTransferred()) /
taskSnapshot.getTotalByteCount();
progressBar.setProgress((int)progress);
mTvMessage.setText(String.format("%s%%", progress));
}
})
.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
@Override
public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
progressBar.setVisibility(View.GONE);
}
})
.addOnSuccessListener (new OnSuccessListener<UploadTask.TaskSnapshot> () {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Snackbar.make (container, R.string.main_message_upload_succes, Snackbar.LENGTH_LONG).show ();
taskSnapshot.getStorage ().getDownloadUrl ().addOnSuccessListener (new OnSuccessListener<Uri> () {
@Override
public void onSuccess(Uri uri) {
savePhotoUrl2 (uri);
Barber barber = new Barber ();
String image = uri.toString ();
barber.setImage (image);
closePhoto.setVisibility (View.VISIBLE);
mTvMessage.setText (R.string.main_message_done);
}
});
}
}).addOnFailureListener (new OnFailureListener () {
@Override
public void onFailure(@NonNull Exception e) {
Snackbar.make (container, R.string.main_message_upload_error, Snackbar.LENGTH_LONG).show ();
}
});
}
private void savePhotoUrl2(Uri downloadUri) {
mDatabaseReference.setValue (downloadUri.toString ());
}
private void goToSelectAuth5() {
Intent intent = new Intent (fotodni.this, fotoDNI2.class);
startActivity (intent);
}
private void getClientInfo(){
mBarberProvider.getBarber (mAuthProvider.getId ()).addListenerForSingleValueEvent (new ValueEventListener () {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists ()){
String name = dataSnapshot.child ("dni").getValue ().toString ();
nameProfile.setText (name);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}