I would like to check if the user in the database exists. with this line of codes, it says that it exists and also that it does not exist. I want to make the code read-only if the name exists in one of the registers
enter image description here
Firebase database
private void Criar_Conta() {
databaseReference_users.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
if (snapshot.child("usuario").getValue().equals(Usuario.getText().toString()) && snapshot.getKey().equals(Usuario.getText().toString()) && snapshot.getKey().equals(snapshot.child("usuario").getValue())) {
Toast.makeText(Sign_Up.this, "Usuário Existente", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(Sign_Up.this, "Gravar ...", Toast.LENGTH_SHORT).show();
//Gravar_Dados();
}
}
} else {
Gravar_Dados();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(Sign_Up.this, databaseError.getMessage(), Toast.LENGTH_LONG).show();
Swipe.setRefreshing(true);
}
});
This is my code sample I hope this helps you
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String phoneTxt = phone.getText().toString();
final String passwordTxt = password.getText().toString();
if (phoneTxt.isEmpty() || passwordTxt.isEmpty()){
Toast.makeText(Login.this, "Please Enter Your Phone Number Or Password", Toast.LENGTH_SHORT).show();
}else {
databaseReference.child("users").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.hasChild(phoneTxt)){
final String getpassword = snapshot.child(phoneTxt).child("password").getValue(String.class);
if (getpassword.equals(passwordTxt)){
Toast.makeText(Login.this, "Successfully login! ", Toast.LENGTH_SHORT).show();
startActivity(new Intent(Login.this,HomeScreen.class));
finish();
}
else{
Toast.makeText(Login.this, "Wrong Password", Toast.LENGTH_SHORT).show();
}
}
else {
Toast.makeText(Login.this, "Wrong Phone Number!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
});
To be able to check if a specific user exists in the database, you should only perform a get(), and not attach a ValueEventListener. Assuming that the users are direct children of your Firebase Realtime Database root, in code, will be as simple as:
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
String usuario = Usuario.getText().toString();
DatabaseReference usuarioRef = db.child(usuario);
usuarioRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
DataSnapshot snapshot = task.getResult();
if(snapshot.exists()) {
Log.d("TAG", "User exists.");
} else {
Log.d("TAG", "User doesn't exist.");
}
} else {
Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
}
}
});
Related
I am trying to add some users in my real time firebase data base, I want to check that by email address which is an User attribute, the problem is that it is adding duplicates. I have an button To add in my database
DAOUser daoUser = new DAOUser();//database accessObject
registerAccountButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (emailField.getText().toString().equals("") || passwordField.getText().toString().equals("") || repeatPasswordField.getText().toString().equals("")) {
Toast.makeText(getApplicationContext(), "Please complete all fields!", Toast.LENGTH_SHORT).show();
} else if (!Objects.equals(passwordField.getText().toString(), repeatPasswordField.getText().toString())) {
Toast.makeText(getApplicationContext(), "Passwords does not match!", Toast.LENGTH_SHORT).show();
} else {
addUser(daoUser, emailField.getText().toString(), passwordField.getText().toString());
}
}
});
The method to add in database:
public void addUser(DAOUser daoUser, String inputMail, String inputPassword) {
daoUser.getDatabaseReference().child("User").orderByChild("email").equalTo(inputMail).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
Toast.makeText(getApplicationContext(), "User already exists!", Toast.LENGTH_SHORT).show();
} else {
User newUser = new User(inputMail, inputPassword, false);
try {
daoUser.add(newUser).addOnSuccessListener(suc -> {
Toast.makeText(getApplicationContext(), "Successfully registered user!", Toast.LENGTH_SHORT).show();
}).addOnFailureListener(er -> {
Toast.makeText(getApplicationContext(), "Unable to register user!", Toast.LENGTH_SHORT).show();
});
} catch (UserIsNullException e) {
e.printStackTrace();
System.out.println("User is null");
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(getApplicationContext(), "User DataBase error !", Toast.LENGTH_SHORT).show();
}
});
}
The database looks like this:
I am trying to find if the data already exist in the database. However it doesn't enter the loop. It always go to the else
This is my validation part, it always goes to the else part
full code is in pastebin
private void validate(final String Song) {
final DatabaseReference RootRef;
RootRef = FirebaseDatabase.getInstance().getReference();
RootRef.addListenerForSingleValueEvent(new ValueEventListener()
{
public void onDataChange(DataSnapshot dataSnapshot)
{
if (!(dataSnapshot.child("Participants").child(Song).exists()))
{
HashMap<String, Object> userdataMap = new HashMap<>();
userdataMap.put("song", Song);
RootRef.child("Participants").child(Song).updateChildren(userdataMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
if (task.isSuccessful())
{
Toast.makeText(Register.this, "This song already exists.", Toast.LENGTH_SHORT).show();
}
}
});
}
else {
Toast.makeText(Register.this, "Your have choosed your song", Toast.LENGTH_SHORT).show();
// Toast.makeText(Register.this, "Please try again.", Toast.LENGTH_SHORT).show();
}}
public void onCancelled(DatabaseError databaseError) {
}
});
}
RootRef = FirebaseDatabase.getInstance().getReference().child("Participants").child(Song);
RootRef.addListenerForSingleValueEvent(new ValueEventListener()
{
public void onDataChange(DataSnapshot dataSnapshot)
{
if (dataSnapshot.exists())
{
Toast.makeText(Register.this, "This song already exists.", Toast.LENGTH_SHORT).show();
}
else {
HashMap<String, Object> userdataMap = new HashMap<>();
userdataMap.put("song", Song);
RootRef.setValue(userdataMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
if (task.isSuccessful())
{
Toast.makeText(Register.this, "This song successfully added", Toast.LENGTH_SHORT).show();
}
}
});
}}
public void onCancelled(DatabaseError databaseError) {
}
});
If you want to check exist a song, you can give it as a reference. If datasnapshot is exists then your database has the song. If not, you can add the song to the database.
This's the database structure
Database Reference
DatabaseReference referSales;
referSales = FirebaseDatabase.getInstance().getReference("Sales");
Username Validation (Including Password Validation )
referSales.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(!(edtPassword.getText().toString()).equals(edtConfirmPassword.getText().toString())) {
loadingDialog.dismiss();
Toast.makeText(Registration.this, "Password and Confirm Password are not identical!", Toast.LENGTH_SHORT).show();
if(dataSnapshot.child(edtUsername.getText().toString()).exists()){
loadingDialog.dismiss();
Toast.makeText(Registration.this, "Username has been used!", Toast.LENGTH_SHORT).show();
}
Update Database
When the username entered is not duplicated with the username stored in the database, the password and confirm password are identical, the new user information will be added to the database.
}else{
loadingDialog.dismiss();
final Sales salesperson = new Sales(edtFirstName.getText().toString(),edtLastName.getText().toString(),
edtPhoneNo.getText().toString(),edtEmail.getText().toString(), edtUsername.getText().toString(),
edtPassword.getText().toString(),edtConfirmPassword.getText().toString());
referSales.child(edtUsername.getText().toString()).setValue(salesperson).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> salesperson) {
if(salesperson.isSuccessful()){
Toast.makeText(Registration.this, "Added Successfully!", Toast.LENGTH_SHORT).show();
finish();
}
}
});
}
}
You can query the database for the to check if the username has already been used in your database.
Query query = databaseReference.child("users").orderByChild("userName")
.equalTo(edtUserName.getText().toString().trim();
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
//user exist
Toast.makeText(getApplicationContext(),"Usename Has been used" ,
Toast.LENGTH_LONG).show();
}else{
//CREATE THE USER
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
private void userSign() {
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
String message = Objects.requireNonNull(task.getException()).getMessage();
Toast.makeText(Start.this, "Error occured: " + message, Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
else
{
Query DatabaseQuery = databaseReference.child("Users").child("Customer").orderByChild("email").equalTo(CLemail.getText().toString().trim());
DatabaseQuery.addListenerForSingleValueEvent(new ValueEventListener()
{
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
if (dataSnapshot.exists())
{
for (DataSnapshot user : dataSnapshot.getChildren())
{
User usersBean = user.getValue(User.class);
if (!usersBean.password.equals(CLpassword.getText().toString().trim()))
{
CLpassword.setError("Password is Wrong!");
CLpassword.requestFocus();
}
else
{
Intent intent = new Intent(Start.this, Home.class);
startActivity(intent);
dialog.setMessage("Loging please wait");
dialog.setIndeterminate(true);
dialog.show();
}
}
}
else {
Toast.makeText(Start.this, "User not found", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError)
{
Toast.makeText(Start.this, "Email not found", Toast.LENGTH_LONG).show();
}
});
dialog.dismiss();
Intent intent = new Intent(Start.this, Home.class);
startActivity(intent);
}
}
});
}
How can I see if there is an equal value in a child and not save if it exists.
I tried doing this here but it did not work:
How can I check if a value exists already in a Firebase data class Android
FirebaseAuth autenticacao = ConfiguracaoFirebase.getFirebaseAutenticacao();
final String idUsuario = CustomBase64.codificarBase64(autenticacao.getCurrentUser().getEmail());
DatabaseReference firebase = ConfiguracaoFirebase.getFirebaseDatabase().child("historico").child(idUsuario);
firebase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild("id")) {
Toast.makeText(getActivity(), "Exist", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity(), "No Exist", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Create yourself another function that pushes the data to firebase and call it from inside your listener. (in this example, create the function pushValueToFirebase)
FirebaseAuth autenticacao = ConfiguracaoFirebase.getFirebaseAutenticacao();
final String idUsuario = CustomBase64.codificarBase64(autenticacao.getCurrentUser().getEmail());
DatabaseReference firebase = ConfiguracaoFirebase.getFirebaseDatabase().child("historico");
firebase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Boolean exists = false;
for (DataSnapshot child : dataSnapshot.getChildren()) {
if (child.getKey().equals(idUsario) {
exists = true;
}
}
if (!exists) {
//Your code here to push idUsario
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Try this:
FirebaseAuth autenticacao = ConfiguracaoFirebase.getFirebaseAutenticacao();
final String idUsuario = CustomBase64.codificarBase64(autenticacao.getCurrentUser().getEmail());
DatabaseReference firebase = ConfiguracaoFirebase.getFirebaseDatabase().child("historico").child(idUsuario).child("id");
firebase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Toast.makeText(getActivity(), "Exist", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity(), "No Exist", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Add the child id to the reference above child("historico").child(idUsuario).child("id") then use exists() to check if this dataSnapshot is in your database.