I am facing the error: cannot find symbol method getDownloadUrl() [duplicate] - java

This question already has an answer here:
Cannot Resolve method getDownloadUrl() [duplicate]
(1 answer)
Closed 3 years ago.
Plzz help me to solve te problem. This is the line:
String thumb_download_url=thumb_task.getResult().getDownloadUrl().toString();
And the code is as below:
StorageReference filepath=mStorageReference.child("profile_image").child(uid+".jpg");
final StorageReference thumb_file_path=mStorageReference.child("profile_image").child("thumbs").child(uid+".jpg");
//------STORING IMAGE IN FIREBASE STORAGE--------
filepath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()){
#SuppressWarnings("VisibleForTests")
final String downloadUrl= task.getResult().getDownloadUrl().toString();
UploadTask uploadTask = thumb_file_path.putBytes(thumb_bytes);
//---------- STORING THUMB IMAGE INTO STORAGE REFERENCE --------
uploadTask.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> thumb_task) {
#SuppressWarnings("VisibleForTests")
String thumb_download_url=thumb_task.getResult().getDownloadUrl().toString();
if(thumb_task.isSuccessful()){
Map update_HashMap=new HashMap();
update_HashMap.put("image",downloadUrl);
update_HashMap.put("thumb_image",thumb_download_url);
//--------ADDING URL INTO DATABASE REFERENCE--------
mDatabaseReference.updateChildren(update_HashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
mProgressDialog.dismiss();
Toast.makeText(SettingActivity.this, "Uploaded Successfuly...", Toast.LENGTH_SHORT).show();
}
else{
mProgressDialog.dismiss();
Toast.makeText(getApplicationContext(), " Image is not uploading...", Toast.LENGTH_SHORT).show();
}
}
});
}
else{
mProgressDialog.dismiss();
Toast.makeText(getApplicationContext(), " Error in uploading Thumbnail..", Toast.LENGTH_SHORT).show();
}
}
});

You get the following error in Android Studio:
cannot find symbol method getDownloadUrl()
Because when you call getResult() method on the thumb_task object, the type of object that is returned is UploadTask.TaskSnapshot and as you can see there no getDownloadUrl() method in this class, hence the error. To get the download url in a correct way, please see my answer from the following post:
How to get the download url from Firebase Storage?

Related

Firebase authentication with onCompleteListener not working

I am trying to implement a basic android authentication system with Firebase. The following is my code:
Toast.makeText(MainActivity.this, "BEFORE ON-COMPLETE", Toast.LENGTH_SHORT).show(); //this shows up
mAuth.signInWithEmailAndPassword(emailInputted, passInputted).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toast.makeText(MainActivity.this, "in OnComplete", Toast.LENGTH_SHORT).show(); //this does not show up
if(task.isSuccessful()){
Intent i = new Intent(MainActivity.this, Dashboard.class);
i.putExtra("EMAIL", emailInputted);
Toast.makeText(MainActivity.this, "Login Successful", Toast.LENGTH_SHORT).show();
startActivity(i);
} else {
Toast.makeText(MainActivity.this, "Please check email/password", Toast.LENGTH_SHORT).show();
}
}
});
Toast.makeText(MainActivity.this, "after OnComplete", Toast.LENGTH_SHORT).show(); //this shows up
I took this code from the official Firebase docs, but for some reason it is not working. The onComplete method is not being called for some reason. I can see the "before on-Complete" and "after on-complete" toasts, but not the "in OnComplete" one. I have added the users in my authentication table in the firebase console, and I am positive that I am entering the correct password.
After using the debugger, I saw that my code just skips over the onComplete() method, and does not even get to the isSuccessful() method. How do I fix this?
Thanks in advance!
Follow this, I hop you will get your answer.
lBut = findViewById(R.id.log_btn);
lBut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String a = usrn.getText().toString().trim();
String b = pswd.getText().toString().trim();
if (TextUtils.isEmpty(a) && TextUtils.isEmpty(b)) {
usrn.setError("Empty Email !!");
pswd.setError("Empty Password !!");
lBut.setClickable(false);
} else {
lBut.setClickable(true);
mAuth.signInWithEmailAndPassword(a, b).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#SuppressLint("ShowToast")
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(getApplicationContext(), "Successfully Login!!", Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), HomeP.class);
ProgressBar prb = findViewById(R.id.progressBar);
prb.setVisibility(View.VISIBLE);
startActivity(i);
finish();
} else
Toast.makeText(getApplicationContext(), "Check Error And Try Again!!", Toast.LENGTH_SHORT).show();
}
});
}
}
});
This is the Event on the Login Button, you have more doubt then reply me.
So it fixed itself after I restarted my computer. No code changes. Maybe Android Studio was being wacky.

Is there a way to edit username and email via code in android studio?

I was wondering if there was a way to edit the name and email via code in Android Studio, to change it in Cloud Firestore. I made a program where it only changes the name in real-time and when logged off, and logged in again it changes back to the previous one which is in Cloud Firestore.
vardas is an EditText field in the app design.
My code:
public void updateProfile(final View view) {
view.setEnabled(false);
vardas1 = vardas.getText().toString();
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
UserProfileChangeRequest request = new UserProfileChangeRequest.Builder()
.setDisplayName(vardas1)
.build();
firebaseUser.updateProfile(request)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
view.setEnabled(true);
Toast.makeText(Profile.this, "SÄ—kmingai atnaujintas profilis", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
view.setEnabled(true);
Log.e(TAG, "onFailure: ", e.getCause());
}
});
}
I was wondering if there was a way to edit the name and email via code in Android Studio, to change it in Cloud Firestore.
Yes, there is. According to the official documentation regarding how to update a document in Cloud Firestore:
To update some fields of a document without overwriting the entire document, use the update() method.
Assuming you want to update the name and email of the authenticated user that exists at the following reference:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference usersRef = rootRef.collection("users");
DocumentReference uidRef = usersRef.document(uid);
Try the following lines of code:
uidRef.update(
"name", "John",
"email", "john#email.com"
).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "DocumentSnapshot successfully updated!");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error updating document", e);
}
});
The result of using this is code, is the update of the name property with "John".
What you are doing in your code is nothing else than updating the name in the FirebaseUser object. That operation is not related in any way with Firestore. So updating the FirebaseUser it doesn't mean that the user will be also updated in the Firestore database. There are two different separate operations that are not related.

How to fix the firebase signup authentication? [duplicate]

This question already has answers here:
Android auth firebase error: Local module descriptor class for com.google.firebase.auth not found
(5 answers)
Closed 3 years ago.
I'm creating an apps for my final year project. So i want to use login and signup features. But when i enter the details of the signup, its keep fail and do not direct the data to the firebase.
Signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (validate()){
String Email = email.getText().toString().trim();
String Password = password.getText().toString().trim();
firebase.createUserWithEmailAndPassword(Email, Password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
Toast.makeText(Signup.this, "Signup successful", Toast.LENGTH_SHORT).show();
startActivity(new Intent(Signup.this, LoginPage.class));
}
else
{
Toast.makeText(Signup.this, "Signup failed", Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
So, is there anything that i have to change?
make sure to initialize the FirebaseAuth object
FirebaseAuth firebase = FirebaseAuth.getInstance();
and Enable the email method in Firebase console
Make sure that you enabled email as an authentication method on firebase portal authentication section.

Load image from firebase storage into image view

In my app users are able to send text and images to other users and now i also want when a user clicks on the sent or received image they will be taken to another activity were the image will be loaded into an image view for the user.
So i added a click listener to the image in my adapter like this
void bind(Messages message) {
String message_type = message.getType();
String user_id = message.getFrom();
String msg_id = message.getKey();
if (message_type.equals("text")) {
messageText.setText(message.getMessage());
// Format the stored timestamp into a readable String using method.
timeText.setText(DateUtils.formatDateTime(message.getTime()));
// DatabaseReference messageRef = mRootRef.child("messages").child(mCurrentUserId).child(user_id).child()
recieved_image.setVisibility(View.INVISIBLE);
// nameText.setText(message.getSender().getNickname());
// Insert the profile image from the URL into the ImageView.
// Utils.displayRoundImageFromUrl(mContext, message.getSender().getProfileUrl(), profileImage);
}else {
messageText.setVisibility(View.INVISIBLE);
recieved_image.setVisibility(View.VISIBLE);
Picasso.with(recieved_image.getContext()).load(message.getMessage()).into(recieved_image);
recieved_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), MessageImageViewerActivity.class);
intent.putExtra("message_id",msg_id);
view.getContext().startActivity(intent);
}
});
with the aim of transferring the message id to the next activity which should be used to locate and load the image from firebase storage like this
msgImage = findViewById(R.id.MsgImageView);
mAuth = FirebaseAuth.getInstance();
final String message_id = getIntent().getStringExtra("message_id");
mRootRef = FirebaseDatabase.getInstance().getReference();
mCurrentUserId = mAuth.getCurrentUser().getUid();
mImageStorage.child("message_images").child(message_id).getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()){
String ima = task.getResult().toString();
// Picasso.with(MessageImageViewerActivity.this).load(ima).into(msgImage);
Glide.with(MessageImageViewerActivity.this)
.load(ima)
.into(msgImage);
}
}
});
but it is returning an error that the path is invalid. this is the logcat error message.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.storage.StorageReference com.google.firebase.storage.StorageReference.child(java.lang.String)' on a null object reference
at com.mani.eric.quickchat.ui.MessageImageViewerActivity.onCreate(MessageImageViewerActivity.java:60)
at android.app.Activity.performCreate(Activity.java:7327)
at android.app.Activity.performCreate(Activity.java:7318)
please what I'm trying to do, is it possible?
or what I'm i not doing right.
You need to do the following:
StorageReference mImageStorage = FirebaseStorage.getInstance().getReference();
First get the reference to the firebase storage, then access the child that you created in the firebase storage console.
mImageStorage.child("message_images").child(message_id).getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()){
String ima = task.getResult().toString();
// Picasso.with(MessageImageViewerActivity.this).load(ima).into(msgImage);
Glide.with(MessageImageViewerActivity.this)
.load(ima)
.into(msgImage);
}
}
});

Best way to get the downloadUrl of thumbnail generated by Firebase Cloud Function

StorageReference newfilepath = mStorage.child("User Submission Images").child(user_id).child("photo1g.jpg");
newfilepath.putFile(photo1ImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
final Uri dwnldUri = task.getResult().getDownloadUrl();
businessDBRef.child(user_id).child("photos1").setValue(dwnldUri.toString());
StorageReference thumbpath = mStorage.child("User Submission Images").child(user_id);
thumbpath.child("thumb_photo1v.jpg").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
businessDBRef.child(user_id).child("thumb1").setValue(uri.toString());
}
});
mProgess.dismiss();
Toast.makeText(getApplicationContext(), "Upload Successful", Toast.LENGTH_SHORT).show();
}
});
After the image gets uploaded i try to pass the download url of the thumbnail into the database but i assume that my code executes faster than the creation of the thumbnail so i get this
StorageException has occurred.
Object does not exist at location.
When checking the Firebase storage the thumbnail is there with the download url accessible. Is there any workaround for this? maybe a way to wait for the thumbnail to generate first and then get the download URl??

Categories

Resources