I want to get the DownloadUrl from an image I uploaded to Firebase but when I try loading it later, I only get a not found exception:
public class ProfileActivity extends AppCompatActivity{
private static final int CHOOSE_IMAGE = 200;
//Initialize items
EditText inputUsername, inputBirthday;
FloatingActionButton mainaction;
FloatingActionButton homeaction;
FloatingActionButton profileaction;
StorageReference profileimageRef;
String profileimageurl;
Button actionSaveProfile;
FirebaseAuth mAuth;
ProgressBar progressBar;
ImageView profileimage;
Boolean isfabopen;
Uri uriProfileImage;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
isfabopen = false;
mainaction = findViewById(R.id.fab_expand);
homeaction = findViewById(R.id.fab_home);
profileaction = findViewById(R.id.fab_profile);
inputUsername = findViewById(R.id.input_username);
inputBirthday = findViewById(R.id.input_birthday);
actionSaveProfile = findViewById(R.id.action_save_profile);
profileimage = findViewById(R.id.profile_image);
progressBar = findViewById(R.id.progressbar);
mAuth = FirebaseAuth.getInstance();
//Expand, collapse menu
mainaction.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!isfabopen)
{
ShowFab();
}else
{
CloseFab();
}
}
});
profileimage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showImageChooser();
}
});
homeaction.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(ProfileActivity.this, MainActivity.class));
}
});
actionSaveProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveUserData(v);
}
});
loadUserData();
}
private void loadUserData() {
FirebaseUser user = mAuth.getCurrentUser();
//If no profile picture found
if(user.getPhotoUrl() != null)
{
String photoUrl = user.getPhotoUrl().toString();
//Set profile picture
Glide.with(this)
.load(user.getPhotoUrl().toString())
.into(profileimage);
}
//If no username found
if(user.getDisplayName() != null)
{
String username = user.getDisplayName();
//Insert display name
inputUsername.setText(user.getDisplayName());
}
}
private void saveUserData(View v)
{
String name = inputUsername.getText().toString().trim();
String birthtday = inputBirthday.getText().toString().trim();
//Check if has content
if(name.isEmpty())
{
Snackbar.make(v, R.string.message_username_empty, Snackbar.LENGTH_SHORT)
.setAction("Action", null).show();
inputUsername.requestFocus();
}else if(birthtday.isEmpty()) {
Snackbar.make(v, R.string.message_birthday_empty, Snackbar.LENGTH_SHORT)
.setAction("Action", null).show();
inputBirthday.requestFocus();
}
//Get user
FirebaseUser user = mAuth.getCurrentUser();
//Upload information
if(user != null && profileimageurl != null)
{
UserProfileChangeRequest profileChangeRequest = new UserProfileChangeRequest.Builder()
.setDisplayName(name)
.setPhotoUri(Uri.parse(profileimageurl))
.build();
Log.wtf("ImageURL3", profileimageurl);
//Show progressbar
progressBar.setVisibility(View.VISIBLE);
user.updateProfile(profileChangeRequest).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
//Hide progressbar
progressBar.setVisibility(View.GONE);
if(task.isSuccessful())
{
Toast.makeText(ProfileActivity.this, R.string.message_profile_updated, Toast.LENGTH_SHORT).show();
}else
{
Toast.makeText(ProfileActivity.this, task.getException().getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
//When got activity result from showImageChooser
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//Check if result is ok
if(requestCode == CHOOSE_IMAGE && resultCode == RESULT_OK && data !=null && data.getData() != null)
{
//Save uri of image
uriProfileImage = data.getData();
try
{
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uriProfileImage);
profileimage.setImageBitmap(bitmap);
uploadToFirebase();
}catch (Exception ex)
{
ex.printStackTrace();
}
}
}
private void uploadToFirebase() {
//Select destination filename, folder
profileimageRef = FirebaseStorage.getInstance().getReference("profilepictures/" + System.currentTimeMillis() + ".jpg");
Log.wtf("ImageURL", profileimageRef.toString());
//Upload image
if(uriProfileImage != null)
{
//Show progressbar
progressBar.setVisibility(View.VISIBLE);
profileimageRef.putFile(uriProfileImage).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
//Hide progressbar
progressBar.setVisibility(View.GONE);
//Check if was successful
if(task.isSuccessful())
{
//Set profile image url
profileimageurl = task.getResult().toString();
Log.wtf("ImageURL2", profileimageurl);
}else
{
Toast.makeText(ProfileActivity.this, task.getException().getLocalizedMessage() , Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void showImageChooser()
{
//Create chooser
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
//Start chooser activity and wait for result
startActivityForResult(Intent.createChooser(intent, getString(R.string.label_profile_pic_chooser)), CHOOSE_IMAGE);
}
private void ShowFab() {
//Bool for menu open
isfabopen = true;
//Set buttons visible
homeaction.setVisibility(View.VISIBLE);
profileaction.setVisibility(View.VISIBLE);
//Rotate main button
mainaction.animate().rotation(135f);
//Expanding to top
homeaction.animate().translationY(getResources().getDimension(R.dimen.standard_100)).rotation(0f);
profileaction.animate().translationY(getResources().getDimension(R.dimen.standard_55)).rotation(0f);
}
private void CloseFab() {
//Bool for menu closed
isfabopen = false;
//Hide buttons
homeaction.setVisibility(View.VISIBLE);
profileaction.setVisibility(View.VISIBLE);
//Rotate main button
mainaction.animate().rotation(0f);
//Collapsing
homeaction.animate().translationY(getResources().getDimension(R.dimen.standard_0)).rotation(135f);
profileaction.animate().translationY(getResources().getDimension(R.dimen.standard_0)).rotation(135f);
}
//Check if user is logged in
#Override
protected void onStart() {
super.onStart();
//Check if user is already loggged in
if(mAuth.getCurrentUser() == null)
{
finish();
startActivity(new Intent(ProfileActivity.this, LoginActivity.class));
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
//Go back to home activity
finish();
startActivity(new Intent(ProfileActivity.this, MainActivity.class));
}
}
XML Code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<RelativeLayout
android:id="#+id/relativeLayout2"
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="#color/colorPrimary"
android:backgroundTint="#color/colorPrimary"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<de.hdodenhof.circleimageview.CircleImageView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/profile_image"
android:layout_width="156dp"
android:layout_height="156dp"
android:src="#drawable/camera_placeholder"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/relativeLayout2">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingLeft="#dimen/standard_23"
android:paddingRight="#dimen/standard_23">
<EditText
android:id="#+id/input_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#color/colorProfileAccent"
android:hint="#string/label_username"
android:inputType="textPersonName"
android:paddingBottom="15dp"
android:textColor="#color/colorProfileAccent"
android:textColorHint="#color/colorProfileAccent" />
<EditText
android:id="#+id/input_birthday"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#color/colorProfileAccent"
android:hint="#string/label_birthday"
android:inputType="textPersonName"
android:paddingBottom="15dp"
android:textColor="#color/colorProfileAccent"
android:textColorHint="#color/colorProfileAccent" />
<Button
android:id="#+id/action_save_profile"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="7dp"
android:background="#drawable/rounded_btn_profile"
android:text="#string/apply_changes"
android:textColor="#color/colorProfileText" />
</LinearLayout>
<ProgressBar
android:id="#+id/progressbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:visibility="gone" />
</RelativeLayout>
<android.support.design.widget.CoordinatorLayout
android:id="#+id/coordinatorLayout"
android:layout_width="wrap_content"
android:layout_height="197dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent">
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab_home"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/standard_23"
android:rotation="90"
android:visibility="gone"
app:fabSize="mini"
app:srcCompat="#drawable/ic_home" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab_profile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/standard_23"
android:rotation="0"
android:translationY="#dimen/standard_55"
android:visibility="gone"
app:fabSize="mini"
app:srcCompat="#drawable/ic_account_box" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab_expand"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
app:fabSize="normal"
app:srcCompat="#drawable/ic_add" />
</android.support.design.widget.CoordinatorLayout>
</android.support.constraint.ConstraintLayout>
I only get a java.io.FileNotFoundException: No such file or directory exception. Earlier I tried saving it with an Success-Listener as it's shown here: https://stackoverflow.com/a/50743192/6274419. But that also hadn't worked because the function doesn't exist in the newer Firebase version.
In general I want to display a profile picture and the username which are saved to Firebase and retrieved on next application startup.
Thanks in Advance!
It takes some time to upload the image in firebase. So you can only retrieve the image when it is completely saved in database. Please call the loadUserData() method in OnSuccess and let me know if it works.
private void uploadToFirebase() {
//Select destination filename, folder
profileimageRef = FirebaseStorage.getInstance().getReference("profilepictures/" + System.currentTimeMillis() + ".jpg");
Log.wtf("ImageURL", profileimageRef.toString());
//Upload image
if(uriProfileImage != null)
{
//Show progressbar
progressBar.setVisibility(View.VISIBLE);
profileimageRef.putFile(uriProfileImage).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
//Hide progressbar
progressBar.setVisibility(View.GONE);
//Check if was successful
if(task.isSuccessful())
{
//Set profile image url
profileimageurl = task.getResult().toString();
loadUserData();
Log.wtf("ImageURL2", profileimageurl);
}else
{
Toast.makeText(ProfileActivity.this, task.getException().getLocalizedMessage() , Toast.LENGTH_SHORT).show();
}
}
});
Solved it now by using another structure/method for retrieving the url with a UploadTask:
private void uploadToFirebase() {
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReference();
//Select destination filename, folder
final StorageReference profileimageRef = storageRef.child("profilepictures/" + System.currentTimeMillis() + ".jpg");
UploadTask uploadTask = profileimageRef.putFile(uriProfileImage);
Log.wtf("ImageURL", profileimageRef.toString());
//Upload image
if(uriProfileImage != null)
{
//Show progressbar
progressBar.setVisibility(View.VISIBLE);
Task<Uri> uriTask = 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();
}
return profileimageRef.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
progressBar.setVisibility(View.GONE);
if(task.isSuccessful()) {
profileimageurl = task.getResult().toString();
}
}
});
}
}
Related
Hi guys I'm trying to upload 2(two) images on firebase with captions but it only uploads the first successfully then the field for 2nd image box (nimagetrail2) copies the bitmap on the 1st image box (nimagetrial) on the database. Can someone help me fix this so that each image gets its own bitmap?
XML file
<ImageView
android:id="#+id/imagetrial"
android:layout_width="85dp"
android:layout_height="85dp"
android:layout_marginTop="32dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/id" />
<ImageView
android:id="#+id/imagetrail2"
android:layout_width="85dp"
android:layout_height="85dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imagetrial"
app:srcCompat="#drawable/payment_l" />
<EditText
android:id="#+id/editcap"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:text="Name"
app:layout_constraintEnd_toEndOf="#+id/imagetrail2"
app:layout_constraintStart_toStartOf="#+id/imagetrail2"
app:layout_constraintTop_toBottomOf="#+id/imagetrail2" />
<EditText
android:id="#+id/editcap2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:text="Name"
app:layout_constraintEnd_toEndOf="#+id/editcap"
app:layout_constraintStart_toStartOf="#+id/editcap"
app:layout_constraintTop_toBottomOf="#+id/editcap" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="Button"
app:layout_constraintEnd_toEndOf="#+id/editcap2"
app:layout_constraintStart_toStartOf="#+id/editcap2"
app:layout_constraintTop_toBottomOf="#+id/editcap2" />
Java code
private ImageView nimagetrial, nimagetrial2;
private EditText neditcap,neditcap2;
private Button nsave;
private Bitmap bitmap,bitmap1;
private
Uri filepath,filepath1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_n_trial);
nimagetrial = findViewById(R.id.imagetrial);
nimagetrial2 = findViewById(R.id.imagetrail2);
neditcap = findViewById(R.id.editcap);
neditcap2 = findViewById(R.id.editcap2);
nsave = findViewById(R.id.button3);
nimagetrial.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ImagePicker.Companion.with(nTrial.this)
.crop()
.compress(1040)
.maxResultSize(1270,1270)
.start(10);
}
});
nimagetrial2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ImagePicker.Companion.with(nTrial.this)
.crop()
.compress(1040)
.maxResultSize(1270,1270)
.start(20);
}
});
nsave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
savetrialData();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 10 && resultCode == RESULT_OK){
filepath = data.getData();
try{
InputStream inputStream=getContentResolver().openInputStream(filepath);
bitmap= BitmapFactory.decodeStream(inputStream);
nimagetrial.setImageBitmap(bitmap);
}catch (Exception ex)
{
}
}else if (requestCode == 20 && resultCode == RESULT_OK){
filepath1 = data.getData();
try {
InputStream inputStream1 = getContentResolver().openInputStream(filepath1);
bitmap1 = BitmapFactory.decodeStream(inputStream1);
nimagetrial2.setImageBitmap(bitmap1);
}catch (Exception ex){
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void savetrialData() {
ProgressDialog dialog = new ProgressDialog(this);
dialog.setTitle("Trail Uploader");
dialog.show();
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference uploader = storage.getReference("ntrial"+new Random().nextInt(50));
uploader.putFile(filepath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(#NonNull UploadTask.TaskSnapshot taskSnapshot) {
uploader.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(#NonNull Uri uri) {
dialog.dismiss();
FirebaseDatabase mFD = FirebaseDatabase.getInstance();
DatabaseReference mDR = mFD.getReference("Trial");
nTrailModel obj = new nTrailModel(neditcap.getText().toString(), neditcap2.getText().toString(),uri.toString(),uri.toString());
mDR.child(neditcap.getText().toString()).setValue(obj);
neditcap.setText("");
neditcap2.setText("");
nimagetrial.setImageResource(R.drawable.id);
nimagetrial2.setImageResource(R.drawable.payment_l);
}
});
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot snapshot) {
float percent = (100*snapshot.getBytesTransferred())/snapshot.getTotalByteCount();
dialog.setMessage(" Uploadind T_T: "+(int)percent+" %");
}
});
}
}
I am not able to display an image inside the imageview in fragment.
I have grant all the permission of storage.
Code executes without any error but doesn't display an image.
Am i doing anything wrong please help.
i have display whole code here.
public class PrescriptionUploadFragment extends Fragment implements View.OnClickListener {
private static final int REQUEST_PERMISSION_CODE = 111;
private static final int PICK_IMAGE_REQUEST = 1;
private ExtendedFloatingActionButton eFabUpload, eFabChooseFile;
private EditText etDescriptionUpload;
private ImageView imgPrescriptionUploads;
private ProgressBar pbPrescriptionUpload;
private ChangeFragment changeFragment;
private InternetCheck internetCheck;
private FirebaseAuth mAuth;
private FirebaseUser mUser;
private DatabaseReference mDatabaseReference;
private StorageReference mStorageReference, ref;
private String UserID = "";
private Uri mImageUri;
private String id;
public PrescriptionUploadFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAuth = FirebaseAuth.getInstance();
mUser = mAuth.getCurrentUser();
UserID = mUser.getUid();
mDatabaseReference = FirebaseDatabase.getInstance().getReference("Prescription").child(UserID);
mStorageReference = FirebaseStorage.getInstance().getReference("Prescription").child(UserID);
internetCheck = new InternetCheck(getActivity());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_prescription_upload, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
InitializeViews(view);
}
private void InitializeViews(View view) {
eFabUpload = (ExtendedFloatingActionButton) view.findViewById(R.id.fabUploadPrescription);
eFabUpload.setOnClickListener(this);
eFabChooseFile = (ExtendedFloatingActionButton) view.findViewById(R.id.fabChooseFile);
eFabChooseFile.setOnClickListener(this);
etDescriptionUpload = (EditText) view.findViewById(R.id.etDescriptionUplaod);
pbPrescriptionUpload = (ProgressBar) view.findViewById(R.id.pbPrescriptionUpload);
imgPrescriptionUploads = (ImageView) view.findViewById(R.id.imgPrescriptionUploads);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
changeFragment = (ChangeFragment) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() + " must implement MyInterface");
}
}
#Override
public void onDetach() {
super.onDetach();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.fabChooseFile:
onClickChooseFile();
break;
case R.id.fabUploadPrescription:
onClickUploadPrescription();
break;
}
}
private void onClickChooseFile() {
if (CheckingPermissionIsEnabled()) {
Intent intentCamera = new Intent();
intentCamera.setType("image/*");
intentCamera.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intentCamera, PICK_IMAGE_REQUEST);
} else {
RequestMultiplePermission();
}
}
private void onClickUploadPrescription() {
if (mImageUri != null && internetCheck.checkConnection()){
id = mDatabaseReference.push().getKey();
ref = mStorageReference.child(id).child(System.currentTimeMillis() +"." + getExtension(mImageUri) );
ref.putFile(mImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
PrescriptionUpload prescriptionUpload = new PrescriptionUpload(id ,mImageUri ,
etDescriptionUpload.getText().toString().trim());
mDatabaseReference.child(id).setValue(prescriptionUpload).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
changeFragment.changeFrag("PRESCRIPTION_MAIN_FRAGMENT");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
pbPrescriptionUpload.setProgress((int) progress);
}
});
} else {
Toast.makeText(getActivity(), "Not an Image !", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null) {
mImageUri = data.getData();
if (mImageUri != null){
imgPrescriptionUploads.setImageURI(mImageUri);
} else {
Toast.makeText(getActivity(), "Image not selected !", Toast.LENGTH_SHORT).show();
}
}
}
private String getExtension(Uri uri) {
ContentResolver cr = getActivity().getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cr.getType(uri));
}
public boolean CheckingPermissionIsEnabled() {
int FirstPermissionResult = ContextCompat.checkSelfPermission(getActivity().getApplicationContext(), INTERNET);
int FifthPermissionResult = ContextCompat.checkSelfPermission(getActivity().getApplicationContext(), ACCESS_WIFI_STATE);
int EighthPermissionResult = ContextCompat.checkSelfPermission(getActivity().getApplicationContext(), READ_EXTERNAL_STORAGE);
int NinthPermissionResult = ContextCompat.checkSelfPermission(getActivity().getApplicationContext(), WRITE_EXTERNAL_STORAGE);
return FirstPermissionResult == PackageManager.PERMISSION_GRANTED &&
FifthPermissionResult == PackageManager.PERMISSION_GRANTED &&
EighthPermissionResult == PackageManager.PERMISSION_GRANTED &&
NinthPermissionResult == PackageManager.PERMISSION_GRANTED;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_PERMISSION_CODE:
if (grantResults.length > 0) {
boolean INTERNET = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean ACCESS_WIFI_STATE = grantResults[1] == PackageManager.PERMISSION_GRANTED;
boolean READ_EXTERNAL_STORAGE = grantResults[2] == PackageManager.PERMISSION_GRANTED;
boolean WRITE_EXTERNAL_STORAGE = grantResults[3] == PackageManager.PERMISSION_GRANTED;
if (INTERNET && ACCESS_WIFI_STATE && READ_EXTERNAL_STORAGE && WRITE_EXTERNAL_STORAGE) {
Toast.makeText(getActivity(), "Permission Granted", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity(), "Permission Denied", Toast.LENGTH_LONG).show();
}
}
break;
}
}
private void RequestMultiplePermission() {
// Creating String Array with Permissions.
ActivityCompat.requestPermissions(getActivity(), new String[]
{
INTERNET,
ACCESS_WIFI_STATE,
READ_EXTERNAL_STORAGE,
WRITE_EXTERNAL_STORAGE
}, REQUEST_PERMISSION_CODE);
}
}
and xml code
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:theme="#style/Theme.MaterialComponents"
tools:context=".PrescriptionUploadFragment">
<ImageView
android:id="#+id/imgPrescriptionUploads"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="24dp"
android:layout_marginTop="24dp"
android:layout_marginEnd="24dp"
android:layout_marginBottom="24dp"
android:scaleType="centerCrop"
app:layout_constraintBottom_toTopOf="#+id/DescriptionUpload"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/DescriptionUpload"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="24dp"
android:layout_marginEnd="24dp"
android:layout_marginBottom="16dp"
android:gravity="center"
app:layout_constraintBottom_toTopOf="#+id/pbPrescriptionUpload"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
<EditText
android:id="#+id/etDescriptionUplaod"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/et_description" />
</com.google.android.material.textfield.TextInputLayout>
<ProgressBar
android:id="#+id/pbPrescriptionUpload"
style="#style/Widget.MaterialProgressBar.ProgressBar.Horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="24dp"
android:layout_marginEnd="24dp"
android:layout_marginBottom="16dp"
android:indeterminate="true"
app:layout_constraintBottom_toTopOf="#+id/linearLayout3"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<LinearLayout
android:id="#+id/linearLayout3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="24dp"
android:layout_marginEnd="24dp"
android:layout_marginBottom="16dp"
android:gravity="center"
android:orientation="horizontal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
<com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton
android:id="#+id/fabChooseFile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:layout_marginEnd="20dp"
android:background="#color/colorPrimaryDark"
android:backgroundTint="#color/colorPrimaryDark"
android:shadowColor="#color/colorPrimary"
android:text="#string/fabChooseFile"
android:textAlignment="center"
android:textColor="#color/colorText"
android:textColorLink="#color/colorPrimaryDark"
app:rippleColor="#color/colorText"
app:tint="#color/colorPrimaryDark" />
<com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton
android:id="#+id/fabUploadPrescription"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:background="#color/colorPrimaryDark"
android:backgroundTint="#color/colorPrimaryDark"
android:shadowColor="#color/colorPrimary"
android:text="#string/fabUpload"
android:textAlignment="center"
android:textColor="#color/colorText"
android:textColorLink="#color/colorPrimaryDark"
app:rippleColor="#color/colorText"
app:tint="#color/colorPrimaryDark" />
</LinearLayout>
enter code here
I am trying to get a list of images from a folder that I created in my FirebaseStorage bucket. There are total of 20 images and while the app gets all the images, I want to show a ProgressBar. Problem is I don't even see the progressbar before it gets dismissed. I believe this is something related to asynchronous calls that FirebaseStorage uses and I tried to solve it by using AsyncTask but no luck.
private void getBigFlagsFromFirebase() {
bigFlagsList = new ArrayList<>();
progressBar.setVisibility(View.VISIBLE);
if (Utils.isInternetConnectionAvailable(this)) {
FirebaseStorage storage = FirebaseStorage.getInstance("gs://big-quiz-adrien.appspot.com/");
StorageReference storageReference = storage.getReference().child("level1_data/big_flags");
storageReference.listAll().addOnSuccessListener(new OnSuccessListener<ListResult>() {
#Override
public void onSuccess(final ListResult listResult) {
final AtomicInteger filesCount = new AtomicInteger(listResult.getItems().size());
for (final StorageReference file : listResult.getItems()) {
file.getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
bigFlagsList.add(uri);
if (filesCount.decrementAndGet() == 0) {
progressBar.setVisibility(View.GONE);
Toast.makeText(QuestionActivity.this, "Size: " + bigFlagsList.size(), Toast.LENGTH_SHORT).show(); //this gives me 20
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
if (filesCount.decrementAndGet() == 0) {
progressBar.setVisibility(View.GONE);
Toast.makeText(QuestionActivity.this, "Something went wrong. Please try again later.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(QuestionActivity.this, "Something went wrong. Please try again later.", Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(this, "Please check your internet connection and try again later.", Toast.LENGTH_LONG).show();
}
Toast.makeText(this, "Size: " + bigFlagsList.size(), Toast.LENGTH_SHORT).show(); //this gives me 0
}
This is my xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f7f7f7"
tools:context=".QuestionsActivity">
<ProgressBar
android:id="#+id/progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="gone" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/ads">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/themeName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:background="#drawable/less_border_radius"
android:backgroundTint="#00B050"
android:gravity="center_horizontal"
android:padding="15dp"
android:text="#string/level_1"
android:textColor="#color/white"
android:textSize="20sp"
android:textStyle="bold" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/flagQuestionsList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
tools:listitem="#layout/country_questions_item" />
</LinearLayout>
</ScrollView>
<TextView
android:id="#+id/ads"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#fff"
android:gravity="center_horizontal"
android:padding="15dp"
android:text="Ads Banner"
android:textSize="18sp" />
</RelativeLayout>
So your code seems to be doing the following:
Showing the progress bar.
Adding a success and failure listener for loading your data.
Dismissing the progress bar.
Loading the data is asynchronous, so until the loading succeeds or fails, you want the progress bar to stay displayed, but you're immediately dismissing it after registering the listener. So progressBar.setVisibility(View.GONE) should be inside the onSuccessListener and onFailureListener instead.
[Edit]
The reason your progress bar is dismissed after the first image is loaded is because you aren't waiting for all the images to load. For each result, you're registering a listener, but you dismiss the progress bar right afterwards. You should wait for all the file.getDownloadUri() calls to complete (either by succeeding or failing).
// I'm not sure if these listeners run concurrently and on which threads, so to be safe I'm using an AtomicInteger, feel free to change it to an int if it's thread safe.
final AtomicInteger filesCount = new AtomicInteger(listResult.getItems().size());
for (StorageReference file : listResult.getItems()) {
file.getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
// Do something with the Uri
if (filesCount.decrementAndGet() == 0) {
progressBar.setVisibility(View.GONE);
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
if (filesCount.decrementAndGet() == 0) {
progressBar.setVisibility(View.GONE);
}
}
});
}
You need to do that with FrameLayout as it help you have the progressbar behind the recyclerview so once your image got loaded, the recyclerview will hide
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ProgressBar
android:id="#+id/progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="gone" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/flagQuestionsList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
tools:listitem="#layout/country_questions_item" />
</FrameLayout>
remove progressBar.setVisibility(View.GONE); line from bottom of funcion, and place when you got success/fail callback:
private void getFilesFromFirebase() {
progressBar.setVisibility(View.VISIBLE);
FirebaseStorage storage = FirebaseStorage.getInstance("gs://big-quiz-adrien.appspot.com/");
StorageReference storageReference = storage.getReference().child("level1_data/small_flags");
storageReference.listAll().addOnSuccessListener(new OnSuccessListener<ListResult>() {
#Override
public void onSuccess(final ListResult listResult) {
progressBar.setVisibility(View.GONE);
for (StorageReference file : listResult.getItems()) {
file.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
smallFlagsList.add(uri);
Toast.makeText(QuestionsActivity.this, "Size: " + smallFlagsList.size(), Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressBar.setVisibility(View.GONE);
}
});
}
and also you should maintain the sequence of view based on which view will render on top and which are behind.
Last view will be on top of all view, if no view contain elevation.
I just switched from Facebook auth to Twitter auth. Facebook worked fine, but now that I have this twitter button on my login screen, it won't even make a sound when I click it. Does anybody have any ideas? Is there something that I should put in my manifest to enable this to work properly? I have updated API and Secret keys as well.
public class LoginActivity extends Activity{
private TwitterLoginButton loginButton;
private FirebaseAuth firebaseAuth;
private ProgressDialog progressDialog;
private static final String TAG = "LoginActivity.class";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
TwitterConfig config = new TwitterConfig.Builder(this)
.logger(new DefaultLogger(Log.DEBUG))
.twitterAuthConfig(new TwitterAuthConfig("CONSUMER_KEY", "CONSUMER_SECRET"))
.debug(true)
.build();
Twitter.initialize(config);
loginButton = (TwitterLoginButton) findViewById(R.id.login_button);
loginButton.setCallback(new Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> result) {
progressDialog = new ProgressDialog(LoginActivity.this);
progressDialog.setMessage("Logging you in");
progressDialog.show();
handleTwitterSession(result.data);
}
#Override
public void failure(TwitterException exception) {
// Do something on failure
System.out.println("failed for some reason");
}
});
firebaseAuth = FirebaseAuth.getInstance();
if(firebaseAuth.getCurrentUser() != null){
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
loginButton.onActivityResult(requestCode, resultCode, data);
}
private void handleTwitterSession(TwitterSession session) {
Log.d(TAG, "handleTwitterSession:" + session);
AuthCredential credential = TwitterAuthProvider.getCredential(
session.getAuthToken().token,
session.getAuthToken().secret);
firebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = firebaseAuth.getCurrentUser();
checkUserAndStart();
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(LoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
// ...
}
});
}
private void checkUserAndStart(){
DatabaseReference db = FirebaseDatabase.getInstance().getReference().child("users").child(firebaseAuth.getCurrentUser().getUid()).child("bio");
db.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
progressDialog.dismiss();
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}else{
finish();
progressDialog.dismiss();
startActivity(new Intent(getApplicationContext(), CreateProfileActivity.class));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
and bellow is my simple login button layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_login"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/baseColor"
android:gravity="center"
tools:context="com.morticia.android.pop.activities.LoginActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:padding ="16dp"
android:layout_gravity="center"
android:weightSum="2">
<ImageView
android:layout_width="wrap_content"
android:layout_height="70dp"
android:src="#drawable/maincircmdpi"
android:id="#+id/imageView4" />
<com.twitter.sdk.android.core.identity.TwitterLoginButton
android:id="#+id/login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:clickable="true"/>
</LinearLayout>
</ScrollView>
</RelativeLayout>
Thanks
-T
Rookie move.
Twitter.initialize(this); needs to be above setContentView();
added that at the top and now it works fine.
removed this:
TwitterConfig config = new TwitterConfig.Builder(this)
.logger(new DefaultLogger(Log.DEBUG))
.twitterAuthConfig(new TwitterAuthConfig("CONSUMER_KEY", "CONSUMER_SECRET"))
.debug(true)
.build();
Twitter.initialize(config);
-T
I believe there is a way for changing your password in Firebase but is there a way where the user forgets the password and can be assigned a new one or re-authenticated using email or SMS OTP. I checked out on the net but couldn't seem to find one.
If there is a way how can it be implemented, what all function calls need to be made. Could you direct me with an example.
It sounds like you're looking to send a password reset email. See this example from the Firebase documentation:
FirebaseAuth.getInstance().sendPasswordResetEmail("user#example.com")
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "Email sent.");
}
}
});
Reset Android FireBase Password
Java File
public class ResetPasswordActivity extends AppCompatActivity {
private EditText inputEmail;
private Button btnReset, btnBack;
private FirebaseAuth auth;
private ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reset_password);
inputEmail = (EditText) findViewById(R.id.email);
btnReset = (Button) findViewById(R.id.btn_reset_password);
btnBack = (Button) findViewById(R.id.btn_back);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
auth = FirebaseAuth.getInstance();
btnBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
btnReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = inputEmail.getText().toString().trim();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplication(), "Enter your registered email id", Toast.LENGTH_SHORT).show();
return;
}
progressBar.setVisibility(View.VISIBLE);
auth.sendPasswordResetEmail(email)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(ResetPasswordActivity.this, "We have sent you instructions to reset your password!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(ResetPasswordActivity.this, "Failed to send reset email!", Toast.LENGTH_SHORT).show();
}
progressBar.setVisibility(View.GONE);
}
});
}
});
}
}
XML FILE
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:fitsSystemWindows="true"
tools:context=".LoginActivity">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:gravity="center"
android:orientation="vertical"
android:padding="#dimen/activity_horizontal_margin">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:padding="10dp"
android:text="#string/lbl_forgot_password"
android:textColor="#android:color/white"
android:textSize="20dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:gravity="center_horizontal"
android:padding="#dimen/activity_horizontal_margin"
android:text="#string/forgot_password_msg"
android:textColor="#android:color/white"
android:textSize="14dp" />
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_marginTop="20dp"
android:hint="#string/hint_email"
android:inputType="textEmailAddress"
android:textColor="#android:color/white"
android:textColorHint="#android:color/white" />
</android.support.design.widget.TextInputLayout>
<!-- Login Button -->
<Button
android:id="#+id/btn_reset_password"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dip"
android:background="#color/colorAccent"
android:text="#string/btn_reset_password"
android:textColor="#android:color/black" />
<Button
android:id="#+id/btn_back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:background="#null"
android:text="#string/btn_back"
android:textColor="#color/colorAccent" />
</LinearLayout>
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_gravity="center|bottom"
android:layout_marginBottom="20dp"
android:visibility="gone" />
</android.support.design.widget.CoordinatorLayout>
Copied and pasted of documentation:
FirebaseAuth auth = FirebaseAuth.getInstance();
String emailAddress = "user#example.com";
auth.sendPasswordResetEmail(emailAddress)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "Email sent.");
}
}
});
This link to the docs should help you out:
DOCUMENTATION
In short, Firebase has a method to use called changePassword, follow the link to find out how to implement it.
Try this method
private void resetpasswoord() {
FirebaseAuth auth = FirebaseAuth.getInstance();
String emailaddress = resest_email.getText().toString();
auth.sendPasswordResetEmail(emailaddress)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "Email sent.");
Toast.makeText(getApplicationContext(), "Check Your Email", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(ForgotPasswordActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
if Unity try this than
string emailaddress = resest_email.text;
FirebaseAuth.DefaultInstance.SendPasswordResetEmailAsync(emailaddress).ContinueWith((task =>
{
if (task.IsCompleted)
{
Debug.Log("Email sent.");
}
if (task.IsFaulted)
{
Firebase.FirebaseException e =
task.Exception.Flatten().InnerExceptions[0] as Firebase.FirebaseException;
GetErrorMessage((AuthError)e.ErrorCode);
return;
}
}));
}
void GetErrorMessage(AuthError errorcode)
{
string msg = "";
msg = errorcode.ToString();
print(msg);
}
Below is the simple method to send the reset password link on user email address with progress dialog (sometime firebase took time to complete reset password request because of slow internet connection on client side, so progress dialog will be helpful)
public void resetUserPassword(String email){
FirebaseAuth mAuth = FirebaseAuth.getInstance();
final ProgressDialog progressDialog = new ProgressDialog(ForgotPasswordActivity.this);
progressDialog.setMessage("verifying..");
progressDialog.show();
mAuth.sendPasswordResetEmail(email)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Reset password instructions has sent to your email",
Toast.LENGTH_SHORT).show();
}else{
progressDialog.dismiss();
Toast.makeText(getApplicationContext(),
"Email don't exist", Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
});
}
If Kotlin is your language of choice you can use this:
val fAuth = FirebaseAuth.getInstance()
fAuth.sendPasswordResetEmail(email).addOnCompleteListener({ listener ->
if (listener.isSuccessful) {
// Do something when successful
} else {
// Do something when not successful
}
})
If you are doing it in Flutter, use this:
#override
Future<void> resetPassword(String email) async {
await _firebaseAuth.sendPasswordResetEmail(email: email);
}