I want to store all the user info into firebase and pass the email and password to firebase auth and insert image to firebase, but here I get an error at taskSnapshot.getDownloadUrl().toString());
And I also not sure this is the correct way to pass user email and password to firebase auth or not
public void AddUser(final String UserEmail, final String Username, final String Password,
final String PhoneNumber, final String confirmPassword, final String Address) {
//first we encode the email into "," to enable check the firebase database
String email = UserEmail.replace(".", ",");
Userdatabase = FirebaseDatabase.getInstance().getReference("User").child(email);
Log.d("UserEmail", Userdatabase.toString());
Userdatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
String value = dataSnapshot.getValue(String.class);
Log.i(TAG, "UserEmail : " + value + " Had Already Exist");
Toasty.warning(getApplicationContext(), "The Email you use already Exist !", Toast.LENGTH_SHORT, true).show();
return;
}
if (!dataSnapshot.exists()) {
if (imageUri != null) {
StorageReference fileReference = storageReference.child(System.currentTimeMillis()
+ "." + getFileExtension(imageUri));
mUploadTask = fileReference.putFile(imageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
}
}, 500);
Toast.makeText(Signup.this, "Register successful", Toast.LENGTH_LONG).show();
final User user = new User(Address, confirmPassword, UserEmail, Password, PhoneNumber, Username,
taskSnapshot.getDownloadUrl().toString());
Userdatabase.setValue(user);
}
});
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
return;
}
});
firebaseAuth.createUserWithEmailAndPassword(UserEmail, Password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressDialog.dismiss();
if (!task.isSuccessful()) {
Log.i(TAG, "Buyer FirebaseAuth Register : Fail");
Toasty.error(getApplicationContext(), "The Email you use already Exist !", Toast.LENGTH_SHORT, true).show();
} else {
Log.i(TAG, "Buyer FirebaseAuth Register : Success");
UserEmail.replace(".", ",");
final User user = new User(Address, confirmPassword, UserEmail, Password, PhoneNumber, Username);
Userdatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists()) {
Userdatabase.setValue(user);
Log.i(TAG, "FirebaseDatabase Add Buyer : Success");
Toasty.success(getApplicationContext(), "Register Complete", Toast.LENGTH_SHORT, true).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.w(TAG, "Database Error");
}
});
}
}
});
}
}
Here is the problem taskSnapshot.getDownloadUrl().toString()
The latest Firebase Library delivers the download url by calling the upload reference in an asychronous task
Here is the complete code
private String link;
mUploadTask = fileReference.putFile(imageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
fileReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri downloadUri) {
link = downloadUri.toString;
Toast.makeText(Signup.this, "Register successful", Toast.LENGTH_LONG).show();
final User user = new User(Address, confirmPassword, UserEmail, Password, PhoneNumber, Username,
link));
Userdatabase.setValue(user);
}
});
}
});
Related
I'm building a gallery app with firebase.
My problem is that when I delete the image, it deletes the document from firebase, but it does not delete it from the screen and the other images are copied on the screen, I could not handle it, I will show you the example below.
THİS GALLERY ADAPTER
#Override
public void onBindViewHolder(#NonNull GalleryHolder holder, int position) {
Picasso.get().load(galleryAdapterArrayList.get(position).downloadUrl).into(holder.imageView);
}
public class GalleryHolder extends RecyclerView.ViewHolder{
public Gallery gallery;
public CheckBox checkBox;
ImageView imageView;
public FirebaseFirestore firebaseFirestore;
public FirebaseUser firebaseUser;
public FirebaseAuth firebaseAuth;
public String Docıd;
public DocumentSnapshot snapshot;
public CollectionReference collectionReference;
public GalleryHolder(#NonNull View itemview) {
super(itemview);
imageView=itemview.findViewById(R.id.gallerLayoutimageview);
firebaseFirestore=FirebaseFirestore.getInstance();
firebaseAuth=FirebaseAuth.getInstance();
firebaseUser=FirebaseAuth.getInstance().getCurrentUser();
itemview.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
PopupMenu popupMenu=new PopupMenu(v.getContext(),v);
popupMenu.setGravity(Gravity.END);
popupMenu.getMenu().add(R.string.sil).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
DocumentReference documentReference=firebaseFirestore.collection("Gallery").document(firebaseUser.getUid()).collection("myGallery").document(galleryAdapterArrayList.get(getPosition()).docId);
documentReference.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
System.out.println("dsadad");
notifyDataSetChanged();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(v.getContext(),R.string.notSilinmedi,Toast.LENGTH_SHORT);
}
});
return false;
}
});
popupMenu.show();
return false;
}
});
}
}
}
THİS GALLERY ACTIVITY
public void getData() {
firebaseFirestore.collection("Gallery").document(firebaseUser.getUid()).collection("myGallery").orderBy("date", Query.Direction.DESCENDING).addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot value, #Nullable FirebaseFirestoreException error) {
if (error != null) {
Toast.makeText(getApplicationContext(), error.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
if (value != null) {
for (DocumentSnapshot snapshot : value.getDocuments()) {
Map<String, Object> data = snapshot.getData();
String downloadUrl = (String) data.get("downloadUrl");
String docId = (String) data.get("docId");
checkBox=findViewById(R.id.checkimages);
GalleryModel galleryModel=new GalleryModel(docId,downloadUrl,checkBox);
galleryModelArrayList.add(galleryModel);
}
galleryAdapter.notifyDataSetChanged();
}
}
});
}
before deleting images
after deleting images
Reset activity
I'm trying to make a feature in my Android studio app which allows users to book appointment with a fixed list of doctors through Firebase realtime database. The problem is that FirebaseAuth.getInstance().getCurrentUser().getUid() is always pointing to same ID and so instead of new appointment details being added via children nodes in the parent node, the existing details in children nodes are being overwritten. Here's my code-
DoctorList.java-
public class DoctorList extends AppCompatActivity {
TextView doc1,doc2,doc3,doc4;
FirebaseAuth mAuth;
DatabaseReference patUser;
ProgressDialog loader;
FirebaseDatabase database= FirebaseDatabase.getInstance();
String Date;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doctor_list);
Intent intent = getIntent();
// receive the value by getStringExtra() method
// and key must be same which is send by first
// activity
String email = intent.getStringExtra("message_key");//patient email
doc1=findViewById(R.id.doc1);
doc2=findViewById(R.id.doc2);
doc3=findViewById(R.id.doc3);
doc4=findViewById(R.id.doc4);
loader = new ProgressDialog(this);
mAuth = FirebaseAuth.getInstance();
FirebaseUser user= mAuth.getInstance().getCurrentUser();
patUser= database.getReference().child("Patient Appointments");
doc1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loader.setMessage("Please wait....");
loader.setCanceledOnTouchOutside(false);
loader.show();
Intent intent= new Intent( DoctorList.this, Book.class);
intent.putExtra("message_key1", "elise#doc.com");
intent.putExtra("message_key2", email);
startActivity(intent);
// create the get Intent object
Intent intent1 = getIntent();
// receive the value by getStringExtra() method
// and key must be same which is send by first
// activity
Date = intent1.getStringExtra("message");
//Toast.makeText(PatientPage.this, str, Toast.LENGTH_SHORT).show();
String currentUserId = mAuth.getCurrentUser().getUid();
patUser= database.getReference().child("Patient Appointments").child(currentUserId);
//HashMap userInfo = new HashMap();
HashMap userInfo = new HashMap();
userInfo.put("Date",Date);
userInfo.put("Patient",email);
userInfo.put("Doctor","Dr.Elise Heather");
userInfo.put("Phone","5925866");
userInfo.put("Status","Pending");
patUser.updateChildren(userInfo).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()){
Toast.makeText(DoctorList.this, "Little more to go....", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(DoctorList.this, task.getException().toString(), Toast.LENGTH_SHORT).show();
}
}
});
loader.dismiss();
//Intent intent2= new Intent( DoctorList.this, PatientPage.class);
//startActivity(intent2);
}
});
}
}
Book.java-
public class Book extends AppCompatActivity {
TextView selectedDate;
Button calenderButton,ok;
FirebaseAuth mAuth;
DatabaseReference docUser;
ProgressDialog loader;
FirebaseDatabase database= FirebaseDatabase.getInstance();
String Date;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book);
Intent intent = getIntent();
// receive the value by getStringExtra() method
// and key must be same which is send by first
// activity
String docEmail = intent.getStringExtra("message_key1");
String patEmail = intent.getStringExtra("message_key2");
selectedDate=findViewById(R.id.text);
calenderButton=findViewById(R.id.calender);
ok=findViewById(R.id.ok);
loader = new ProgressDialog(this);
mAuth = FirebaseAuth.getInstance();
FirebaseUser user= mAuth.getInstance().getCurrentUser();
docUser= database.getReference().child("Doctor Schedule");
MaterialDatePicker materialDatePicker=MaterialDatePicker.Builder.datePicker().
setTitleText("Select date").setSelection(MaterialDatePicker.todayInUtcMilliseconds()).build();
calenderButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
materialDatePicker.show(getSupportFragmentManager(),"Tag_Picker");
materialDatePicker.addOnPositiveButtonClickListener(new MaterialPickerOnPositiveButtonClickListener() {
#Override
public void onPositiveButtonClick(Object selection) {
selectedDate.setText(materialDatePicker.getHeaderText());
Date=materialDatePicker.getHeaderText();
}
});
}
});
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Date != null) {
String currentUserId = mAuth.getCurrentUser().getUid();
docUser = database.getReference().child("Doctor Schedule").child(currentUserId);
//HashMap userInfo = new HashMap();
HashMap userInfo = new HashMap();
userInfo.put("Date", Date);
userInfo.put("Patient", patEmail);
userInfo.put("Doctor", docEmail);
userInfo.put("Status", "Pending");
docUser.updateChildren(userInfo).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
Toast.makeText(Book.this, "Appointment booked", Toast.LENGTH_SHORT).show();
Intent intent= new Intent( Book.this, DoctorList.class);
intent.putExtra("message", Date);
startActivity(intent);
} else {
Toast.makeText(Book.this, task.getException().toString(), Toast.LENGTH_SHORT).show();
}
}
});
}
else {
Toast.makeText(Book.this, "Select date!", Toast.LENGTH_SHORT).show();
}
}
});
}
}
Suppose a user with email athy#gmail.com books appointment and in Firebase database there's already details of booking by another user nivi#gm.com . Then the details of the latter user in the parent node (ID) gets overwritten by user athy#gmail.com and it looks like this. I don't think I've written code for overwriting instead of updating since it works fine in other Android studio projects, so I'm guessing FirebaseAuth.getInstance().getCurrentUser().getUid() is the one always pointing to same ID which I've circled in the image.
How do I fix this?
I want to make a login without input form, just use a button that authenticates to the custom field firebase, help me
TextView var_text;
private DatabaseReference ref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
var_text = (TextView) findViewById(R.id.infoText);
ref = FirebaseDatabase.getInstance().getReference().child("karyawan");
}
String phoneID;
public void btnLogin_Click(View view) {
phoneID = phoneID.getBytes().toString();
ref.child(phoneID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
karyawan karyawan = dataSnapshot.getValue(karyawan.class);
if (phoneID.equals(karyawan.getPhoneID())){
Toast.makeText(MainActivity.this, "login sukses", Toast.LENGTH_SHORT).show();
Intent i = new Intent(MainActivity.this, MenuActivity.class);
startActivity(i);
}else {
Toast.makeText(MainActivity.this, "Anda belum terdaftar" , Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError)
{
}
});
}
}
enter image description here
enter image description here
So you want your login information stored on the mobile device? If so just store it as strings and pass those in when you login. Not secure obviously. Something like this:
You will also need to add the credentials to your firebase database. There are also some rules about email and pass words they have to be value e.g. email needs an # with something after it like .com. And I think the passwords needs to be at least length 6.
private void login(String email, String password)
{
String my_username = test;
String my_password = test;
mAuth.signInWithEmailAndPassword(my_username, my_password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {//This is the logging in api
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) //Logged in successfully to firebase
{
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithEmail:success");
FirebaseUser user = mAuth.getCurrentUser();//Identify who is logged in
logged_in_user_string = mAuth.getCurrentUser().getEmail();//Store the logged in user's email address to be displayed
//You are logged in here stare next activity
}
else
{
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithEmail:failure", task.getException());
Log.d(TAG, "Login failed");
}
}
});
}
In my project user can sign in by enter their user name and password only.
But i stuck at forget password option.In my code i use addListenerForSingleValueEvent method for sign up.
I use DatabaseReference for store user info in firebase auto
users = FirebaseDatabase.getInstance().getReference("Users");
this users work like this screen shot
this code is given below:
users.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//replace get method 27.01.19
if (dataSnapshot.child(user.getUserName()).exists()) {
Toast.makeText(MainActivity.this, "User Already Exist", Toast.LENGTH_SHORT).show();
} else {
users.child(user.getUserName())
.setValue(user);
Toast.makeText(MainActivity.this, "Registration Successfully", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
i set a alert dialogue for signUp This is the screen shot of signup
////////for registration dialog////////
private void showDialog() {
AlertDialog.Builder alertdialog = new AlertDialog.Builder(MainActivity.this);
alertdialog.setTitle("Sign Up");
alertdialog.setMessage("Please fill the credentials");
LayoutInflater layoutInflater = this.getLayoutInflater();
View view = layoutInflater.inflate(R.layout.signup, null);
editNewEmail = view.findViewById(R.id.newemail);
editNewUser = view.findViewById(R.id.newUsername);
editNewPassword = view.findViewById(R.id.newpassword);
alertdialog.setView(view);
alertdialog.setIcon(R.drawable.ic_account_circle_black_24dp);
alertdialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertdialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
final User user = new User(editNewUser.getText().toString()
, editNewPassword.getText().toString()
, editNewEmail.getText().toString());
users.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//replace get method 27.01.19
if (dataSnapshot.child(user.getUserName()).exists()) {
Toast.makeText(MainActivity.this, "User Already Exist", Toast.LENGTH_SHORT).show();
} else {
users.child(user.getUserName())
.setValue(user);
Toast.makeText(MainActivity.this, "Registration Successfully", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
dialog.dismiss();
}
});
alertdialog.show();
}
My sign in method is here Screenshot of signIn
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
users.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.child(editUser.getText().toString()).exists()) {
User user = dataSnapshot.child(editUser.getText().toString()).getValue(User.class);
if (user.getPassword().equals(editPassword.getText().toString())) {
Intent intent = new Intent(MainActivity.this, Home.class);
Common.currentUser = user;
startActivity(intent);
finish();
} else
Toast.makeText(MainActivity.this, "Password Wrong", Toast.LENGTH_SHORT).show();
} else
Toast.makeText(MainActivity.this, "Please Register", Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
});
But i stuck to make forget password option that helps user while they forget password and resent password by sending email addressThis is the demo screen shot of forget password
I understand that If i know that how to store email in firebase
authentication then i will manage this.
I try to store email address form signup form but i don't know how to store email in authentication from singnUp form in firebase.
i have clear concept about
mAuth.createUserWithEmailAndPassword(email, password)
.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, "createUserWithEmail:success");
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "createUserWithEmail:failure", task.getException());
Toast.makeText(EmailPasswordActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
updateUI(null);
}
// ...
}
});
but i need to know how to store email in firebase authentication without createUserWithEmailAndPassword
My backend returns this json object to signal a succesful new user registration
{
"error": false,
"message": "You have been successfully registered"
}
and this to signal the account already exists
{
"error": true,
"message": "Sorry, this email already exists"
}
and this on other registration failure
{
"error": true,
"message": "An error occurred!! Please try again"
}
I want to use retrofit:2.0.0-beta2 to make an asynchronous http call and handle the response to take the use to the home page or redirect to the login page accordingly.
Here's my POJO:
public class User {
public final String email, firstname, lastname, city, birthday, gender, password;
public User(final String email, final String firstname, final String lastname,
final String city, final String birthday, final String gender, final String password) {
this.email = email;
this.firstname = firstname;
this.lastname = lastname;
this.city = city;
this.birthday = birthday;
this.gender = gender;
this.password = password;
}
}
Here's my service:
public interface APIService {
#POST("/api/user")
Call<User> createUser(#Body User user);
}
You need to create a extra class to handled response.
public class ResponseApi{
public String error;
public String message;
}
You're inferface
#POST("/api/user")
Call<ResponseApi> createUser(#Body User user);
You need to implement onResponse listener and handle the redirects or any other action inside it.
For example:
protected void loginAttempt(final View v) {
authUser = new HashMap<>();
authUser.put("email", email.getText().toString());
authUser.put("password", password.getText().toString());
Call call = SubApplication.api.authUser(authUser);
call.enqueue(new Callback() {
#Override
public void onResponse(Call call, Response response) {
try {
JSONObject responseObject = new JSONObject(new Gson().toJson(response.body()));
Log.d("LoginActivity", "onResponse: " + responseObject.toString());
if (responseObject.getBoolean("success") == true) {
Toast.makeText(v.getContext(), getString(R.string.error_login_success), Toast.LENGTH_LONG).show();
Intent intent = new Intent(v.getContext(), DashboardActivity.class);
startActivity(intent);
finish();
} else {
Toast.makeText(v.getContext(), getString(R.string.error_login_failed), Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Log.e("LoginActivity", "Exception: " + e);
Toast.makeText(v.getContext(), getString(R.string.error_login_failed), Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call call, Throwable t) {
Log.e("LoginActivity", "onFailure: " + t);
}
});