How to check Firebase data success upload Android? - java

How can I check whether my data has been successfully pushed to Firebase?
I want to push my data like the picture

To know when the write operation is completed or not, you need to use a complete listener. So let's say you want to know when the write operation for your id_data property is completed, please use the followig code:
addReference.child("DataInputManual").child(key).child("id_data").setValue(key)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
//Do what you need to do
} else {
Log.d(TAG, task.getException().getMessage());
}
}
});
You can also use a success listener like this:
addReference.child("DataInputManual").child(key).child("id_data").setValue(key)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
//Do what you need to do
}
});

You can use below code to check success or failure of upload on firebase Storage.
final StorageReference photoRef = FirebaseStorage.getInstance().getReference()
.child("image_folder_on_firebase")
.child("image_name" + ".jpeg");
photoRef.putFile("local pic uri( Object of Uri)").addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
newPicFirebaseUri = taskSnapshot.getStorage().getDownloadUrl().getResult();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});

Related

How to update email from Firebase? UpdateEmail method has been deprecated

I am trying to update my email from FireBase, how can I achive this? updateEmail looks like has been depreacated?
FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
AuthCredential credential= EmailAuthProvider.getCredential(user.getEmail(),edtPassword.getText().toString());
user.reauthenticate(credential).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if(task.isSuccessful()){
FirebaseAuth.getInstance().fetchSignInMethodsForEmail(edtEmail.getText().toString())
.addOnCompleteListener(new OnCompleteListener<SignInMethodQueryResult>() {
#Override
public void onComplete(#NonNull Task<SignInMethodQueryResult> task) {
if(task.isSuccessful()){
if(task.getResult().getSignInMethods().size()==0){
Here--------------------------------->
}else {
Toast.makeText(AccountSettingsActivity.this,"The Email is alread in use",Toast.LENGTH_SHORT).show();
}
}else {
Toast.makeText(AccountSettingsActivity.this,"Task is not successfull in fetch",Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressBar.setVisibility(View.GONE);
Toast.makeText(AccountSettingsActivity.this,"Unable to edt email",Toast.LENGTH_SHORT).show();
}
});
}else {
Toast.makeText(AccountSettingsActivity.this,"Task is not successfull", Toast.LENGTH_LONG).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressBar.setVisibility(View.GONE);
Toast.makeText(AccountSettingsActivity.this,"Unable to update email failure",Toast.LENGTH_LONG).show();
}
});
}
I had the same issu and I found the solution here : How to update email from Firebase in Android?
To retrieve password for credential you can use SharedPreferences.
It worked for me ;)

Global variable value assignment remains the same after re-assignment in function (Android Studio)

programmers, I am very new to android studio and java, in this case, I am trying to upload retrieved user info and store them in firebase database. the retrieve process is successful, and the retrieve URL can be seen after logged. However, the String pathToProfile is not assigned with the URL, when I checked the log, it is null. Thanks in advance!
Global declaration:
String pathToProfile;
Map<String, Object> UserInfo = new HashMap<>();
Function to retrieve the download URL
// retrieved URL should be saved in user document
private void retrieveProfileViaURL () {
profileRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
pathToProfile = uri.toString();
UserInfo.put(PROFILE_URL, pathToProfile);
Log.d(TAG, "retrieve profile image successful" + pathToProfile);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Log.d(TAG, "retrieve profile image failure");
// pathToProfile = "uri download unsuccessful";
}
});
}
Function to upload userinformation to firebase
private void uploadUserInfo(String user, String bioInfo) {
// CollectionReference users = db.collection("users");
String UID = getUserID();
retrieveProfileViaURL();
// UserInfo.put(USERID, UID);
UserInfo.put(USERNAME, user);
UserInfo.put(BIO, bioInfo);
mDocRef.collection("users").document(UID).set(UserInfo)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(USER_INFO, "Document has been saved");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(USER_INFO, "Document was not saved!", e);
}
});
}
All data from the Firebase Database is read asynchronously. You can not get values outside the call. That's why your pathToProfile shows null.
For Better approach you can try something like this.
After the user upload the data it will automatically allow user to write in data with url
private void retrieveProfileViaURL () {
profileRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
pathToProfile = uri.toString();
String UID = getUserID();
UserInfo.put(USERNAME, user);
UserInfo.put(BIO, bioInfo);
UserInfo.put(PROFILE_URL, pathToProfile);
mDocRef.collection("users").document(UID).set(UserInfo)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(USER_INFO, "Document has been saved");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(USER_INFO, "Document was not saved!", e);
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Log.d(TAG, "retrieve profile image failure");
// pathToProfile = "uri download unsuccessful";
}
});
}

Why List<String> are not inserted in Firebase Realtime Database

I created an app and I want to store some images in a Firebase Storage, this is working fine, those images are uploaded, but I want to save their path in the database and those values are not inserted.
Let me show you what I did:
I'm not showing you the entire function. Only the code that points to my problem.
List<String> picturesUrls = new ArrayList<String>(); //This is declared globaly
buttonSigningUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uploadFile(mProfilePic,"profilePicture");
uploadFile(mIdPhoto,"idPicture");
uploadFile(mCriminalRecord,"criminalRecordPicture");
final List<String> pictureUrls = picturesUrls;
mFirebaseAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
final CarrierUser carrierUser;
carrierUser = new CarrierUser(
pictureUrls
);
FirebaseDatabase.getInstance().getReference("User")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(carrierUser).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()) {
Toast.makeText(SignupCarrier.this,"Your request has been sent for approval", Toast.LENGTH_LONG).show();
sendEmail(email, fullname);
openLogin();
}
}
});
}
}
});
}
});
Upload File Function :
private void uploadFile(Uri path,String forWho) {
if(path != null) {
StorageReference fileReference = mStorageRef.child(editemail.getText().toString()+"-"+forWho+"-"+System.currentTimeMillis()+"."+getFileExtension(path));
mUploadTask = fileReference.putFile(path)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
picturesUrls.add(taskSnapshot.getUploadSessionUri().toString());
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(SignupCarrier.this, e.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
}
And the Object:
import java.util.List;
public class CarrierUser {
public List<String> picturesUrls;
public CarrierUser() {
}
public CarrierUser(List<String> picturesUrls) {
this.picturesUrls = picturesUrls;
}
}
I do have another values and fields, but they are inserted, only this list with paths is not. Maybe I did something wrong when I add a path to that list, but I can't figure out what exactly is wrong. Can you please help me out? Thank you very much.

How to get imageUrl from firebase storage to store in firebase realtime database?

Basically I have created a class called 'Club'. I save a new club to firebase realtime database successfully with no real problems, until I want to add an imageURL (called clubImage) from Firebase Storage to my club class.
I am able to succesfully upload my image to Firebase Storage using the below code.
private void uploadImage() {
//upload selected image to database
//code from https://code.tutsplus.com/tutorials/image-upload-to-firebase-in-android-application--cms-29934
if(filePath != null)
{
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
final StorageReference ref = storageReference.child("images/"+ UUID.randomUUID().toString());
ref.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(AddClubActivity.this, "Uploaded", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(AddClubActivity.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+"%");
}
});
}
}
This all works fine. However, in the same method, I also have this code, which is where I try to get my downloadURL for the uploaded image.
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Uri downloadUrl = uri;
clubImage = downloadUrl.toString();
}
});
I know it is inefficient to have two OnSuccessListeners for the same thing, I am just not sure how else to go about both uploading an image and getting the downloadUrl at the same time.
Regardless, this doesn't work, and my new club saves without the clubImage field.
I get the error: E/StorageException: StorageException has occurred.
Object does not exist at location.
Does anyone know how to fix this?
Thanks.
I know it is inefficient to have two OnSuccessListeners for the same thing
You have two tasks that you're trying to complete:
Upload a file
Get the download URL for that file
Since these are two separate tasks, you'll need two OnSuccessListeners. There is nothing inefficient about this, nor are the tasks the same.
The Firebase documentation on getting a download URL after uploading shows precisely how to complete these two tasks in succession:
final StorageReference ref = storageRef.child("images/mountains.jpg");
uploadTask = ref.putFile(file);
Task<Uri> urlTask = uploadTask.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();
}
// Continue with the task to get the download URL
return ref.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
} else {
// Handle failures
// ...
}
}
});
You'll note that this code first completes the uploadTask (which uploads the file) and only then starts a new task to get the download URL. Executing the tasks in this sequence prevents the "Object does not exist at location" error message you get.
try using this:
private Uri ImageUri; //and get image from gallery intent to this ImageUri
...............
StorageReference filePath = FirebaseStorage.getInstance().getReference().child("Club Images").child(ImageUri.getLastPathSegment() + ".jpg");
filePath.putFile(ImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task)
{
if(task.isSuccessful())
{
downloadUrl = task.getResult().getDownloadUrl().toString();
updatetoFirebaseDatabase();
}
else
{
String message = task.getException().getMessage();
}
}
});
...........
create updatetoFirebaseDatabase(String imageUrl) method:
updatetoFirebaseDatabase(String imageUrl){
//implement FirebaseDatabase setvalue method with given image URL
}

In Firebase after uploading Image how can I get Url? [duplicate]

This question already has answers here:
How to get URL from Firebase Storage getDownloadURL
(13 answers)
Closed 1 year ago.
Right now, I'm fetching image from storage of Firebase by using below code:
mStoreRef.child("photos/" + model.getBase64Image())
.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
// Got the download URL for 'photos/profile.png'
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
Toast.makeTextthis, "image not dowloaded", Toast.LENGTH_SHORT).show();
}
});
Is it possible to get this URL which is shown in image?
Follow this link -https://firebase.google.com/docs/storage/android/download-files#download_data_via_url
storageRef.child("users/me/profile.png").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
// Got the download URL for 'users/me/profile.png'
Uri downloadUri = taskSnapshot.getMetadata().getDownloadUrl();
generatedFilePath = downloadUri.toString(); /// The string(file link) that you need
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
}
});
As per the latest firebase changes, here is the updated code:
File file = new File(String.valueOf(imageUri));
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReference().child("images");
storageRef.child(file.getName()).putFile(imageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
pd.dismiss();
Toast.makeText(MyProfile.this, "Image Uploaded Successfully", Toast.LENGTH_SHORT).show();
Task<Uri> downloadUri = taskSnapshot.getStorage().getDownloadUrl();
if(downloadUri.isSuccessful()){
String generatedFilePath = downloadUri.getResult().toString();
System.out.println("## Stored path is "+generatedFilePath);
}}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
pd.dismiss();
}
});
}
that's how I'm getting download link in kotlin android.
ref.putFile(filePath!!)
.addOnSuccessListener {
val result = it.metadata!!.reference!!.downloadUrl;
result.addOnSuccessListener {
var imageLink = it.toString()
}
}
Thats works fine on latest firebase builds
UploadTask uploadTask = ref.putBytes(data);
uploadTask.addOnSuccessListener(new OnSuccessListener<TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
taskSnapshot.getStorage().getDownloadUrl().addOnCompleteListener(
new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
String fileLink = task.getResult().toString();
//next work with URL
}
});
The above method taskSnapshot.getMetadata().getDownloadUrl(); is deprecated and as a substitute provided this alternative:
final StorageReference ref = storageRef.child("images/mountains.jpg");
uploadTask = ref.putFile(file);
Task<Uri> urlTask = uploadTask.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();
}
// Continue with the task to get the download URL
return ref.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
} else {
// Handle failures
// ...
}
}
});
In the past the firebase used getMetadata().getDownloadUrl(), and today they use getDownloadUrl()
It should be used this way:
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
String image = taskSnapshot.getDownloadUrl().toString());
}
});
//kotlin
var uri:Uri
uploadTask.addOnSuccessListener {t ->
t.metadata!!.reference!!.downloadUrl.addOnCompleteListener{task ->
uri = task.result!!
}
}
Yes that's possible !!.
Instead of some creepy complicated lines of code here is my shortcut trick to get that downloadurl from firebase storage in kotlin
Note:Based on the latest firebase release there is no getdownloadurl() or getresult() method (they are the prey of deprecition this time around)
So the the trick i have used here is that by calling UploadSessionUri from the taskSnapshot object which in turn returns the downloadurl along with upload type,tokenid(one which is available for only shorter span of time) and with some other stuffs.
Since we need only download url we can use substring to get downloadurl and concat it with alt=media in order to view the image.
var du:String?=null
var du1:String?=null
var du3:String="&alt=media"
val storage= FirebaseStorage.getInstance()
var storagRef=storage.getReferenceFromUrl("gs://hola.appspot.com/")
val df= SimpleDateFormat("ddMMyyHHmmss")
val dataobj= Date()
val imagepath=SplitString(myemail!!)+"_"+df.format(dataobj)+".jpg"
val imageRef=storagRef.child("imagesPost/"+imagepath)
val baos= ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.JPEG,100,baos)
val data=baos.toByteArray()
val uploadTask=imageRef.putBytes(data)
uploadTask.addOnFailureListener{
Toast.makeText(applicationContext,"Failed To Upload", Toast.LENGTH_LONG).show()
}.addOnSuccessListener { taskSnapshot ->
imageRef.downloadUrl.addOnCompleteListener (){
du=taskSnapshot.uploadSessionUri.toString()
du1=du!!.substring(0,du!!.indexOf("&uploadType"))
downloadurl=du1+du3
Toast.makeText(applicationContext,"url"+downloadurl, Toast.LENGTH_LONG).show()
}
}
Hope it helps !.
This should be how it should be done in kotlin
you need to add an onCompleteListener
putFile(file).addOnSuccessListener {
it.storage.downloadUrl.addOnCompleteListener {
//then you can call it.result.toString()
}
}
This works for me with dependency - implementation 'com.google.firebase:firebase-storage:19.1.0'
ref.putFile(iconUriLocalFilePath)
.addOnSuccessListener(
new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(
UploadTask.TaskSnapshot taskSnapshot)
{
Task<Uri> uri = ref.getDownloadUrl();
String iconPathFirebase = uri.getResult().toString();
}
});
I tried this and it got me the link to review it on the imageview :
storageRef.child("users/me/profile.png").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
// Got the download URL for 'users/me/profile.png'
uri.toString();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
}
});
If you already have download infrastructure based around URLs, or just want a URL to share, you can get the download URL for a file by calling the getDownloadUrl() method on a storage reference.
// Create a storage reference from our app
val storageRef = storage.reference
storageRef.child("users/me/profile.png").downloadUrl.addOnSuccessListener {
// Got the download URL for 'users/me/profile.png'
}.addOnFailureListener {
// Handle any errors
}
firebase documentation

Categories

Resources