Validate if data already exist in firebase - java

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.

Related

How to retrieve data from Firebase in android RealTimeDatabase to update on the basis of regid

I want to retrieve data from my Realtime Database server so that I can update values based on the reg-id (stored this as a child string, not as Auth) I have saved for the user.
I have done this till now
private void updateDatatoFirebase(String regid, String doctor_name, String city,String speciality) {
Map<String, Object> update=new HashMap<>();
update.put("doctor",doctor_name);
update.put("city",city);
update.put("speciality",speciality);
DatabaseReference dbref=FirebaseDatabase.getInstance().getReference();
dbref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot ds : snapshot.getChildren()){
key = snapshot.getKey();
if(checkid.equalsIgnoreCase(regid))
{
dbref.updateChildren(update);
Toast.makeText(need_help.this, "Data in Database updated", Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(need_help.this, "No such id found", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(need_help.this, "Fail to add data " + error, Toast.LENGTH_SHORT).show();
}
});
}
to update but it won't update
and I have saved data like this
private void addDatatoFirebase(String regid, String doctor_name, String city,String speciality) {
root=firebaseDatabase.getReference().child("RegId").child(regid);
HashMap<String, String> usermap=new HashMap<>();
usermap.put("doctor",doctor_name);
usermap.put("city",city);
usermap.put("speciality",speciality);
root.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
root.push().setValue(usermap);
Toast.makeText(need_help.this, "Data in Database updated", Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(need_help.this, "Fail to add data " + error, Toast.LENGTH_SHORT).show();
}
});
To be able to update all children under a particular node, for instance, 1234, you have to pass to the following method, 1234 as the first argument:
private void updateDatatoFirebase(String regid, String doctor_name, String city,String speciality) {
Map<String, Object> update=new HashMap<>();
update.put("doctor",doctor_name);
update.put("city",city);
update.put("speciality",speciality);
DatabaseReference dbref=FirebaseDatabase.getInstance().getReference();
dbref.child("RegId").child(regid).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot ds : snapshot.getChildren()){
ds.getRef().updateChildren(update).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(need_help.this, "Data in Database updated", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(need_help.this, "Failed with an error: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(need_help.this, "Fail to add data " + error, Toast.LENGTH_SHORT).show();
}
});
}
Things to notice:
I have added two extra calls .child("RegId") and .child(regid) call right after the root reference.
I have used the ds to call getRef() and then .updateChildren(update).
I have attached a listener to see if something goes wrong when updating the children under 1234.

Check if the user in the database firebase exists

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!
}
}
});

firebase realtime database push infinite loop error

I'm using firebase authentication with email and password.
So I want to save user data in realtime database .
But when i push the data to database, infinite loop was executing.
I don't know why..
I want to save data like this form and continue saving.
But when I starting, infinite loop is starting
private void createUser(String email, String password,String name, String phone, String
nickname) {
firebaseAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) { //Join Success
Toast.makeText(JoinActivity.this, "Join Success", Toast.LENGTH_SHORT).show();
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(firebaseAuth.getCurrentUser()!=null) {
String email=editTextEmail.getText().toString().trim();
FirebaseUser user=firebaseAuth.getCurrentUser();
String uid=user.getUid();
if(dataSnapshot.child("USER").child("user_info").child(uid).exists()){
Toast.makeText(JoinActivity.this,"already exist",Toast.LENGTH_SHORT).show();
}else{
User user_info = new User(uid, editTextId.getText().toString(), editTextEmail.getText().toString(), editTextPassword.getText().toString(),
editTextname.getText().toString(), editTextNickname.getText().toString(), editTextPhone.getText().toString());
//delete all data
mDatabase.setValue(null);
String key = mDatabase.child("USER").push().getKey();
// mDatabase.child("USER").child("user_info").child(key).setValue(user_info);
Toast.makeText(JoinActivity.this, "save the data", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Intent intent = new Intent(JoinActivity.this, MainActivity.class);
startActivity(intent);
} else { //already exists
Toast.makeText(JoinActivity.this, "already exists", Toast.LENGTH_SHORT).show();
return;
}
}
});
}
}
Instead of :
mDatabase.addValueEventListener(new ValueEventListener() {
Use the following:
mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
This way you will retrieve data only once.

I am trying to use two firebase authentications (client, customer), I need to use firebase auth with database query

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 to get the URL of multiple images in Firebase

I'm storing multiple images at once in Firebase Storage and I need to get the URL of each one of them in the Firebase databse.
Here's the code:
private void SaveVersus() {
comment = Comment.getText().toString();
if (imageUri==null||imageUri2==null){
Toast.makeText(this, "...Select a Image...", Toast.LENGTH_SHORT).show();
}
else if(imageUri!=null&&imageUri2!=null&&imageUri3==null&&imageUri4==null) {
//Save2ImagesFirebase();
List<Uri> uri = Arrays.asList(imageUri,imageUri2);
storeMultipleImages(uri);
}
else if(imageUri!=null&&imageUri2!=null&&imageUri3!=null&&imageUri4==null){
//Save3ImagesFirebase();
List<Uri> uri2 = Arrays.asList(imageUri,imageUri2,imageUri3);
storeMultipleImages(uri2);
}
else if(imageUri!=null&&imageUri2!=null&&imageUri3!=null&&imageUri4!=null){
//Save4ImagesFirebase();
List<Uri> uri3 = Arrays.asList(imageUri,imageUri2,imageUri3,imageUri4);
storeMultipleImages(uri3);
}
}
public void storeImage(Uri imageUri) {
StorageReference filepath = mStorage.child("Versus Images").child(imageUri.getLastPathSegment());
filepath.putFile(imageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()){
downloadURL = task.getResult().getUploadSessionUri().toString();
Toast.makeText(ImageVersus.this, "Versus Published", Toast.LENGTH_SHORT).show();
GetInDB();
}
else{
Toast.makeText(ImageVersus.this, "..Error..", Toast.LENGTH_SHORT).show();
}
}
});
}
private void GetInDB() {
mDatabase.child(current_userID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
String username = dataSnapshot.child("Username").getValue().toString();
HashMap InfoMap = new HashMap<>();
InfoMap.put("username",username);
InfoMap.put("imageUrl",downloadURL);
versusDBRef.child(current_userID).updateChildren(InfoMap);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public void storeMultipleImages(List<Uri> imageUris) {
for (Uri uri : imageUris) {
storeImage(uri);
}
}
The problem is that, in the hashmap, I can only put the URL of one image and I need to get multiple URLs depending on what the amount of pictures the user select, if they chose two, then in the hashmap must be two URL's and so on.

Categories

Resources