E/StorageException: Unable to obtain an upload URL - java

I don't know why I'm getting this exception E/StorageException: Unable to obtain an upload URL whenever it gets to uploading file/image onto Firebase Storage. It's also returning W/NetworkRequest: error sending network request error. Although I don't experience any internet connectivity problems. I've also tried running this with another device but it results in the same thing.
firebaseAuth.createUserWithEmailAndPassword(inputEmail, inputPassword).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
firebaseAuth.getCurrentUser().sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull final Task<Void> task) {
final String uID = firebaseAuth.getCurrentUser().getUid();
if (task.isSuccessful()) {
storageReference = FirebaseStorage.getInstance().getReference("image").child(uID); // for image uploads
storageReference.putFile(image_uri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//image uri is taken care of in the onActivityResult method.
member.setImage_url(taskSnapshot.getUploadSessionUri().toString());
member.setEmail(email.getText().toString().trim());
member.setFname(fname.getText().toString().trim());
member.setLname(lname.getText().toString().trim());
df = FirebaseDatabase.getInstance().getReference("Member").child(uID); //points to the address
df.setValue(member).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
startActivity(new Intent(Register.this, Login.class));
Toast.makeText(Register.this, "Registered successfully, please verify your email.", Toast.LENGTH_LONG).show();
}
});
RprogressBar.setVisibility(View.INVISIBLE);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Register.this, e.getMessage(), Toast.LENGTH_LONG).show();
RprogressBar.setVisibility(View.INVISIBLE);
}
});
} else {
Toast.makeText(Register.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
RprogressBar.setVisibility(View.INVISIBLE);
}
}
});
} else {
Toast.makeText(Register.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
RprogressBar.setVisibility(View.INVISIBLE);
}

I still only have the slightest idea of what is happening but I've seen some other answers from a similar post and they suggested using VPN I'm currently in the Philippines so if anyone is having a similar problem try using VPN.

Related

Firebase upload listeners never get fired

I am building an android application that uploads photos from a device to a Firebase storage. The images are properly uploaded but I can't get the upload listeners to work. I have gone through the documentation here and implemented the exact same solution:
System.out.println("Starting upload");
Uri file = Uri.fromFile(new File("myPath"));
StorageReference Ref = storageRef.child("images/"+file.getLastPathSegment());
uploadTask = Ref.putFile(file);
// Register observers to listen for when the download is done or if it fails
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// NEVER EXECUTES
System.out.println("upload failed");
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// NEVER EXECUTES
System.out.println("upload succeeded");
}
});
I can see the first line printed "Starting upload". But that's it. The same goes for OnCompleteListener if I add it but it's omitted here.
What is going wrong?
Try OnCompleteListener
uploadTask = Ref.putFile(file);
uploadTask.addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
System.out.println("upload succeeded");
} else {
System.out.println("upload failed");
}
}
});

Firebase Storage bug trying to insert data into my database

I have been looking around some questions but can't get to the point of what I'm doing wrong.
I'm trying to upload a file to Firebase storage and then write the download URL inside a node in my database.
Now, this is the weird thing, I'm authenticating with email and password provider, but the weird thing is that the code uploads my image to the storage but keeps looping to place the download link in my database and then just gives me this error:
E/StorageException: StorageException has occurred.
User does not have permission to access this object.
Now, I have checked my rules and since I'm authenticated I tried with this two without any success
service firebase.storage {
match /b/my-bucket.appspot.com/o {
match /{allPaths=**} {
allow read, write: if request.auth != null;
}
}
}
and this one
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if request.auth != null;
}
}
}
Now I tried this one too
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if true;
}
}
}
and still having the same problem.
This is the code I use to upload a file to the storage and place the downloadurl in my database
public void cargarProductoFirebase(final String nombreProducto, final float precioProducto, final Dialog dialog, final ProgressDialog progressDialog, Uri filePath) {
mStorageReference.child("fotos").child(mAuth.getCurrentUser().getUid()).child(filePath.getLastPathSegment()).putFile(filePath).continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw task.getException();
}
return mStorageReference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
Map<String, Object> producto = new HashMap<>();
producto.put("nombreProducto", nombreProducto);
producto.put("precioProducto", precioProducto);
producto.put("imagen",downloadUri.toString());
mDatabase.child("Usuarios").child(mAuth.getCurrentUser().getUid()).child("productos").push().updateChildren(producto).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
dialog.dismiss();
progressDialog.dismiss();
Toast.makeText(mContext, "Se cargo el producto correctamente.", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(mContext, "Error al cargar el producto" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(mContext, "upload failed: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
Stacktrace of the error
2018-10-09 20:32:49.442 9767-9821/com.example.macbook.firebasemvp
E/StorageException: StorageException has occurred.
User does not have permission to access this object.
Code: -13021 HttpResult: 403 2018-10-09 20:32:49.443 9767-9821/com.example.macbook.firebasemvp E/StorageException: {
"error": { "code": 403, "message": "Developer credentials
required." }}
java.io.IOException: { "error": { "code": 403, "message": "Developer credentials required." }}
at com.google.firebase.storage.obfuscated.zzj.zza(com.google.firebase:firebase-storage##16.0.2:455)
at com.google.firebase.storage.obfuscated.zzj.zza(com.google.firebase:firebase-storage##16.0.2:3435)
at com.google.firebase.storage.obfuscated.zzc.zza(com.google.firebase:firebase-storage##16.0.2:65)
at com.google.firebase.storage.obfuscated.zzc.zza(com.google.firebase:firebase-storage##16.0.2:57)
at com.google.firebase.storage.zzc.run(com.google.firebase:firebase-storage##16.0.2:68)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
Also the file is uploaded to the right place but the error continues and can't place that downloadurl to the database
Edit
I shrunk the code and removed the database part and still the same issue
public void cargarProductoFirebase(final String nombreProducto, final float precioProducto, final Dialog dialog, final ProgressDialog progressDialog, Uri filePath) {
mStorageReference.child("fotos").child(mAuth.getCurrentUser().getUid()).child(filePath.getLastPathSegment()).putFile(filePath).continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw task.getException();
}
return mStorageReference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
Log.e(TAG, "onComplete: Success " );
} else {
Toast.makeText(mContext, "upload failed: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
Image:
Also, there is no addOnProgressUpdate like the old storage implementation ?
The problem is caused by your call to getDownloadUrl():
return mStorageReference.getDownloadUrl();
My guess is that mStorageReference points to the root of your Cloud Storage bucket, so you're asking for the download URL of the entire bucket, which isn't allowed.
To solve this, as for the download URL of the StorageReference you actually wrote to:
StorageReference fileReference = mStorageReference.child("fotos").child(mAuth.getCurrentUser().getUid()).child(filePath.getLastPathSegment())
fileReference.putFile(filePath).continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw task.getException();
}
return fileReference.getDownloadUrl();
}
...
Btw: I found this by searching for the "Developer credentials required" from the error message](https://www.google.com/search?q=firebase+storage+"Developer+credentials+required").

Firebase "OnCompleteListener" always returns successful

In my code the OnCompleteListener is always successful, even if I get my device offline, so the data cant get uploaded. How can I get the information that the data is not successful uploaded?
DatabaseReference index = database.getReference("Events").child(event_name).child("comments");
index.push().setValue(new Comment(newComment, userName)).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
finish();
} else {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show();
}
}
});

How to retrieve the download URL of an image from Firebase Storage?

I am watching an old tutorial about Firebase Storage. The getDownloadUrl() method from UploadTask.TaskSnapshot is no longer existent, and the documentation fails to be clear to me.
What I've implemented so far is the upload process and I can confirm it works, but getting the URL is a pain and I can't make the way they explain how to do it because:
1) Creating a Task<Uri> urlTask = uploadTask.add[...]() will result in the following error on the IDE:
I don't understand because it is specified in the docs.
2) Using reference.getDownloadUrl() will display a different URL compared to what is shown on the console when seeing the details of the uploaded image. The download URL the console shows is
https://firebasestorage.googleapis.com/v0/b/chatroom-e44e6.appspot.com/o/chat_photos%2F73185640?alt=media&token=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
while logging will show
com.google.android.gms.tasks.xxx#xxxxxxx
My full code at the moment:
if (requestCode == RC_PHOTO_PICKER) {
if (data != null) {
Toast.makeText(MainActivity.this, "Uploading...", Toast.LENGTH_SHORT).show();
Uri file = data.getData();
final StorageReference reference = mPhotoStorageReference.child(file.getLastPathSegment());
UploadTask upload = reference.putFile(file);
upload.addOnFailureListener(this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "Image could not be uploaded: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}).addOnCompleteListener(this, new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
ChatroomMessage message = new ChatroomMessage(null, mUsername, reference.getDownloadUrl().toString()); // <- com.google.android.gms.tasks.xxx#xxxxxxx
mMessagesDatabaseReference.push().setValue(message);
Toast.makeText(MainActivity.this, "Image uploaded!", Toast.LENGTH_SHORT).show();
}
});
}
}
My app already has Firebase UI implemented to handle login operations, and the rules are
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if request.auth != null;
}
}
}
I put the effort and wasted more time but here is the more generic and working solution
private void uploadImage() {
if (filePath != null) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
final StorageReference ref = storageReference.child("images/" +currentFirebaseUser.getUid() + "");
ref.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
while (!urlTask.isSuccessful());
Uri downloadUrl = urlTask.getResult();
Log.e("uri12",downloadUrl+"This is uri of image download");
Toast.makeText(AddItemActivity.this, "Uploaded", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(AddItemActivity.this, "Failed " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot
.getTotalByteCount());
progressDialog.setMessage("Uploaded " + (int) progress + "%");
}
});
}
}
You have Permission denied error it means you don't have permision for access data from firebase. Please check here
if your security rules is defined public then here is no need for permission and if it isn't public or secured then you need to login by auth before you getting data from firebase and if login success then you can continue your work.
check this it will help you to understanding firebase security rules.
After many attempts, I managed to solve it. This is the implementation:
Uri file = data.getData();
final StorageReference reference = mPhotoStorageReference.child(file.getLastPathSegment());
UploadTask upload = reference.putFile(file);
upload.addOnFailureListener(this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "Image could not be uploaded: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
upload.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw task.getException();
}
return reference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUrl = task.getResult();
ChatroomMessage message = new ChatroomMessage(null, mUsername, downloadUrl.toString());
mMessagesDatabaseReference.push().setValue(message);
Toast.makeText(MainActivity.this, "Image uploaded!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, task.getException().toString(), Toast.LENGTH_SHORT).show();
}
}
});

error with updating user information firebase

so i am creating a sign up page and connect that with firebase users
i am recieving error with updating profile
my code goes as follow:
for creating new user i use
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
Log.v("SignUp", "222222222222222222222222222");
Toast.makeText(SignUp.this, "SignUp failed",
Toast.LENGTH_SHORT).show();
} else {
Log.v("SignUp", "333333333333333333333333333");
uploadImage();
}
}
});
and the uploadImage() method is
public void uploadImage() {
if (image != null) {
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference main = storage.getReferenceFromUrl("link to my account");
StorageReference storageReference = main.child("images/" + image.getLastPathSegment());
UploadTask uploadTask = storageReference.putFile(image);
//addonFailurelistener too
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Log.v("SignUp", "777777777777777777777777");
String download = taskSnapshot.getDownloadUrl().toString();
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.build();
//i tried here with .setDisplayName(name)
//and with setPhotoUri(Uri.parse(download)
FirebaseAuth.getInstance().getCurrentUser().updateProfile(profileUpdates).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.v("SignUp", "8888888888888888888888888888");
addDatabase();
} else {
FirebaseAuth.getInstance().getCurrentUser().delete().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.v("SignUp", "999999999999999999999999999");
Toast.makeText(SignUp.this, "Error Occuered While setting your account", Toast.LENGTH_LONG);
finish();
startActivity(new Intent(SignUp.this, SignUp.class));
} else {
Log.v("SignUp", "..........................");
Toast.makeText(SignUp.this, "Error Cannot be resolved \n please try with another Email", Toast.LENGTH_LONG);
finish();
}
}
});
}
}
});
}
});
}
and my logcat get output like that
V/SignUp: 333333333333333333333333333
V/SignUp: 777777777777777777777777
V/SignUp: ..........................
i followed the firebase guide but looks like i am doing something wrong
any idea why it doesnt work? thanks
i get it automatically resolved after waiting for 24 hours so i am assuming account get blocked for 24h after some number of logIn in a single day

Categories