How to ensure my data is saved on Firebase? - android

I am storing my data in Firebase database in my Android app. However, I am not sure how to check if my data is saved on database and show appropriate message. So far, I tried to check the unique ID created by push and see if it is null or not. But it did not work for me. Any other suggestion?
private void createData(String name){
SnapShotModel ssm = new SnapShotModel(name);
myRef.push().setValue(ssm);
AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert);
} else {
builder = new AlertDialog.Builder(this);
}
builder.setTitle("ERROR!")
.setMessage("Error in saving data. Please try again.")
.setNegativeButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}

How to ensure my data is saved on Firebase?
You can be sure if add a complete listener after you calling setValue() method like this:
myRef.push().setValue(ssm).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "Object successfully added");
} else {
Log.d(TAG, "Error: " + task.getException().getMessage());
}
}
});

If you'd like to know when your data has been committed, you can add a completion listener. Check documentation
ref.setValue("I'm writing data", new Firebase.CompletionListener() {
#Override
public void onComplete(FirebaseError firebaseError, Firebase firebase) {
if (firebaseError == null) {
Show dialog
}
}
});

FirebaseDatabase db;
onCreate
db = FirebaseDatabase.getInstance();
DatabaseReference readDb = db.getReference("Your Channel Name");
readDb.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String value = dataSnapshot.getValue().toString();
Toast.makeText(context, value, Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
When you read this way in your application, you are connected to your database.
DatabaseReference writeDb = db.getReference("Your Channel Name");
writeDb.setValue("Value");
this way you can write
Note: google-services.json don't forget to add.
and build.grandle
implementation 'com.google.firebase:firebase-database:16.0.3'

Related

When I try to save details of user in a class before loggin him using Firebase its giving me Error

I'm working on a project in which I have to save details of the user before logging him/her in her account so that I don't have to fetch his/her detail again and can refer to that class whenever I need their details. It's displaying the toast "Error occurred ! please login again." which means null value or false is being returned. Also after I close the app and open again its moving to next Activity.
signintouserbycredential method
private void signInTheUserByCredential(PhoneAuthCredential credential)
{
firebaseAuth=FirebaseAuth.getInstance();
firebaseAuth.signInWithCredential(credential).addOnCompleteListener(Login_student.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
String curr_user_str=task.getResult().getUser().getUid();
//Store user data in HelperClass for future use
if((curr_user_str.isEmpty())&&(storeUserInfoInHelperClass(curr_user_str)))
{
Toast.makeText(Login_student.this, "Login Successful", Toast.LENGTH_SHORT).show();
startActivity(new Intent(Login_student.this, Home_page.class));
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
finishAffinity();
}
else
{
Toast.makeText(Login_student.this,"Error occurred ! Please login again.",Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(Login_student.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
storeInfoinHelperClass method
int flag=0;// to check if data is stored and if it is stored return true
static HelperClass data;
public boolean storeUserInfoInHelperClass(String curr_user_str) {
reff = FirebaseDatabase.getInstance().getReference("userdetails");
reff.child(curr_user_str).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (data != null) {
data = dataSnapshot.getValue(HelperClass.class);
flag=1;
} else {
flag=0;
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
if(flag==1)
return true;
else
return false;
}

Role base login with Firebase database is failing

I'm doing a project called e-school. It has 4 types of users which uses Firebase authentication and Firebase realtime database to login to their accounts, Anyway, I'm getting issues while working with Firebase realtime database and Firebase authentication. I'm letting users to their respective dashboards comparing the authentication data with the realtime database.
//Registration Code
auth.createUserWithEmailAndPassword(email.getText().toString(), password.getText().toString())
.addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
Users user = new Users();
user.setE_mail(email.getText().toString());
user.setNumber(Phone.getText().toString());
user.setPassword(password.getText().toString());
user.setU_name(username.getText().toString());
users.child("principal").child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(user)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Snackbar.make(rootLayout, "Registration Success",Snackbar.LENGTH_LONG)
.show();
return;
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Snackbar.make(rootLayout, "Registration Failed: "+e.getMessage(), Snackbar.LENGTH_LONG)
.show();
return;
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Snackbar.make(rootLayout, "Failed :"+e.getMessage(),Snackbar.LENGTH_LONG)
.show();
return;
}
});
}
});
//Login COde
auth.signInWithEmailAndPassword(t_email.getText().toString(), t_password.getText().toString())
.addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
id = auth.getUid();
teacherValidation(id);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Snackbar.make(rootLayout,"Authentication Failed", Snackbar.LENGTH_SHORT).show();
}
});
//TeacherValidate
private void teacherValidation(final String id) {
users = db.getInstance().getReference("Users/teachers");
users.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.getKey().equals(id)){
Toast.makeText(MainActivity.this," "+id,Toast.LENGTH_SHORT).show();
Intent it = new Intent(MainActivity.this, teachers.class);
it.putExtra("UID", id);
startActivity(it);
finish();
}else{
Toast.makeText(MainActivity.this, "No Teacher Esxist With the Given Credientialss", Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
It is not necessary to get all teachers details on client side. Instead you can directly check in database for that user, it'll increase the performance of app also.
Just modify teacherValidation method like this.
private void teacherValidation(final String id) {
users = db.getInstance().getReference("Users/teachers").child(id);
users. addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// If below condition checks true,
// that means user exists on teacher node, so probably he/she is a teacher.
if(dataSnapshot.getValue() != null){
Toast.makeText(MainActivity.this," "+id,Toast.LENGTH_SHORT).show();
Intent it = new Intent(MainActivity.this, teachers.class);
it.putExtra("UID", id);
startActivity(it);
finish();
}else{
Toast.makeText(MainActivity.this, "No Teacher Exist With the Given Credientialss", Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
I got this code snippet. Probably addListenerForSingleValueEvent is your method.
Pay special attention in the way the query is built, calling a first child which is the table called "users" and then a second child which is a user with a specific userId. FUser is equivalent to your Users class.
Try it...
private void getFirebaseUserInfo(final String userId, final GetUserInfoListener userInfoListener) {
DatabaseReference userIdReference = getDatabaseReference().child("users").child(userId);
userIdReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
try {
final Users user = dataSnapshot.getValue(FUser.class);
if (!user.email.isEmpty()) {
// Do whatever
} else {
userInfoListener.onSuccess(user);
}
} catch(DatabaseException e) {
userInfoListener.onFailure(new Exception(e.getMessage()));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
userInfoListener.onFailure(new Exception(databaseError.getMessage()));
}
});
}
Also, look at the difference:
Difference between addValueEventListener() and addListenerForSingleValueEvent() of firebase

Firebase database updating child value again and again without meting codition true

In my app there is an option for referrals, I am using the firebase database to update the wallet if referral code matched, but the problem is user account is credting successfully but agent account(who referred )is credting multiple times like over and over continuously and that's the issue,
public void checkreffercode() {
final String refferalcode = editText.getText().toString();
if (refferalcode.equals("")) {
Toast.makeText(ReferalActivity.this, "Refferal code is empty", Toast.LENGTH_LONG).show();
} else {
final DatabaseReference reffercoderef = FirebaseDatabase.getInstance().getReference().child("Reffercode");
final DatabaseReference agentwallet = FirebaseDatabase.getInstance().getReference();
final DatabaseReference userwalletstat = FirebaseDatabase.getInstance().getReference(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("Refferal");
final DatabaseReference userwallet = FirebaseDatabase.getInstance().getReference(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("walletcoin");
userwalletstat.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String statous = dataSnapshot.getValue(String.class);
if (statous == null) {
Toast.makeText(ReferalActivity.this, "data is null in Refferal", Toast.LENGTH_LONG).show();
} else if (statous.equals("notcredited")) {
//here check all the feild....
reffercoderef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child(refferalcode).exists()) {
final String Uid = dataSnapshot.child(refferalcode).getValue(String.class);
userwallet.setValue(String.valueOf(5000));
agentwallet.child(Uid).child("walletcoin").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String agentbalance = dataSnapshot.getValue(String.class);
Integer agentbalinint = Integer.parseInt(agentbalance);
Integer updatedbalu = (agentbalinint + 5000);
agentwallet.child(Uid).child("walletcoin").setValue(String.valueOf(updatedbalu));
userwalletstat.setValue("credited");
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(ReferalActivity.this, "error on updating agent balance", Toast.LENGTH_LONG).show();
}
});
} else {
Toast.makeText(ReferalActivity.this, "Refferal code not found", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(ReferalActivity.this, "Database error on checking refferal code", Toast.LENGTH_LONG).show();
}
});
//last
} else {
Toast.makeText(ReferalActivity.this, "Both wallet has been credited", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(ReferalActivity.this, "Database error on checking account status", Toast.LENGTH_LONG).show();
}
});
}
}
public void updateref(View view) {
Button button=findViewById(R.id.refbutton);
final ProgressDialog progressDialog = new ProgressDialog(ReferalActivity.this);
progressDialog.setMessage("Please wait..");
progressDialog.getActionBar();
progressDialog.setCancelable(false);
progressDialog.show();
checkreffercode();
progressDialog.cancel();
}
Here is my xml code
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Refer code"
android:id="#+id/refercode"
android:inputType="textPersonName"
android:padding="20dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Update"
android:onClick="updateref"
android:layout_gravity="center"
android:id="#+id/refbutton"
android:textColor="#51122e"/>
You are using ValueEventListener on userwalletstat reference. The problem is that with ValueEventListener is that, it gets called every time a value changes under userwalletstat ("referal") child. Inside your else if (statous.equals("notcredited")) condition, you are using another ValueEventListener in which you are setting setting the value like this userwallet.setValue(String.valueOf(5000));
So your first ValueEventListener gets activated because it's a ValueEventListener. So your code is kind of like a recusive function and it is bad. So in order to fix it, you should replace your ValueEventListeners with SingleValueEventListener. You can learn more about them here and scroll down to Read Data Once section.
Basically, you need to replace
userwalletstat.addValueEventListener(new ValueEventListener() {
with
userwalletstat.addListenerForSingleValueEvent(new ValueEventListener() {
and do the same for other listeners like :
reffercoderef.addListenerForSingleValueEvent(new ValueEventListener() {
agentwallet.child(Uid).child("walletcoin").addListenerForSingleValueEvent(new ValueEventListener() {
Also, I don't know how your data structure is setup but it is not a good idea to have a listener inside a listener inside a listener. Maybe you should reorganize your datastructure.

Function addListenerForSingleValueEvent from firebase

Using Firebase Database.
I have a database which stores the registration information for patients.
While registering a new patient, i'm checking whether the person is already registered or not.
The function below checks if a registration for that person is already made or not.
I'm checking this by going to "Users/Phone_no/Patient_name".
If the DataSnapshot is not null registration is already there.
private boolean checkAlreadyRegistered(){
final boolean[] alreadyRegistered = {false};
/*Get the reference*/
mDatabaseReference = FirebaseDatabase.getInstance().getReference("Users/" + childDetails.getPhone() + "/" + childDetails.getPatientName());
mDatabaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d(TAG, "onDataChange: " + dataSnapshot);
if (dataSnapshot.getValue() != null) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Record Already Exists");
builder.setMessage("The current patient is already registered");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
alreadyRegistered[0] = true;
}
});
builder.create();
builder.show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(getContext(), "Some error occured", Toast.LENGTH_LONG).show();
}
});
return alreadyRegistered[0];
}
From saveInDatabase i'm calling the above function
void saveInDatabase(Long patient_id) {
boolean alreadyRegistered = checkAlreadyRegistered();
if (alreadyRegistered) {
resetRegisterFields();
return;
}
mDatabaseReference = FirebaseDatabase.getInstance().getReference("Current_registered_users");
mDatabaseReference.setValue(patient_id + 1);
childDetails.setPatient_id(patient_id);
mDatabaseReference = FirebaseDatabase.getInstance().getReference("Users");
Log.d(TAG, "saveInDatabase: "+mDatabaseReference);
mDatabaseReference.child(childDetails.getPhone()).child(childDetails.getPatientName()).child("Registration Details").setValue(childDetails);
Button bt = (Button) getView().findViewById(R.id.buttonRegister);
resetRegisterFields();
progressDialog.dismiss();
displayPid(patient_id);
bt.setEnabled(true);
.
.
}
What i want to do- Check if a registration based on phone_no/Patient_name is already made or not, if not save the details.
Problem - When a new registration is made it is added to the database, but after that the message "..Already registered", from checkAlreadyRegistered() ->onDataChange is displayed.
Why is that message coming, and how solve it?
All data reading in Firebase happens asynchronously, so I recommend you change your code to something that looks like this:
private void checkAlreadyRegistered(){
/*Get the reference*/
mDatabaseReference = FirebaseDatabase.getInstance().getReference("Users/" + childDetails.getPhone() + "/" + childDetails.getPatientName());
mDatabaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d(TAG, "onDataChange: " + dataSnapshot);
if (dataSnapshot.getValue() != null) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Record Already Exists");
builder.setMessage("The current patient is already registered");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
resetRegisterFields();
}
});
builder.create();
builder.show();
}
else
{
saveInDatabase(patient_id); //TODO change this accordingly
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(getContext(), "Some error occured", Toast.LENGTH_LONG).show();
}
});
}
And your save method:
void saveInDatabase(Long patient_id) {
mDatabaseReference = FirebaseDatabase.getInstance().getReference("Current_registered_users");
mDatabaseReference.setValue(patient_id + 1);
childDetails.setPatient_id(patient_id);
mDatabaseReference = FirebaseDatabase.getInstance().getReference("Users");
Log.d(TAG, "saveInDatabase: "+mDatabaseReference);
mDatabaseReference.child(childDetails.getPhone()).child(childDetails.getPatientName()).child("Registration Details").setValue(childDetails);
Button bt = (Button) getView().findViewById(R.id.buttonRegister);
resetRegisterFields();
progressDialog.dismiss();
displayPid(patient_id);
bt.setEnabled(true);
.
.
}
You have to wait for the response from Firebase. You can add a Callback to run the rest of your code once it's been retrieved. Do something like this:
Create an interface called ServerCallback:
public interface ServerCallback
{
void onSuccess(boolean result);
}
In your checkAlreadyRegistered() method, add the callback so it runs once the data is retrieved from Firebase:
private void checkAlreadyRegistered(final ServerCallback callback){
final boolean[] alreadyRegistered = {false};
/*Get the reference*/
mDatabaseReference = FirebaseDatabase.getInstance().getReference("Users/" + childDetails.getPhone() + "/" + childDetails.getPatientName());
mDatabaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d(TAG, "onDataChange: " + dataSnapshot);
if (dataSnapshot.getValue() != null) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Record Already Exists");
builder.setMessage("The current patient is already registered");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
alreadyRegistered[0] = true;
callback.onSuccess(alreadyRegistered[0]);
}
});
builder.create();
builder.show();
}
else
callback.onSuccess(alreadyRegistered[0]);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(getContext(), "Some error occured", Toast.LENGTH_LONG).show();
}
});
}
Then in your saveInDatabase(), wait for the callback, then run the rest of your code:
void saveInDatabase(Long patient_id) {
boolean alreadyRegistered = checkAlreadyRegistered(new ServerCallback() {
#Override
public void onSuccess(boolean result)
{
if (alreadyRegistered) {
resetRegisterFields();
return;
}
mDatabaseReference = FirebaseDatabase.getInstance().getReference("Current_registered_users");
mDatabaseReference.setValue(patient_id + 1);
childDetails.setPatient_id(patient_id);
mDatabaseReference = FirebaseDatabase.getInstance().getReference("Users");
Log.d(TAG, "saveInDatabase: "+mDatabaseReference);
mDatabaseReference.child(childDetails.getPhone()).child(childDetails.getPatientName()).child("Registration Details").setValue(childDetails);
Button bt = (Button) getView().findViewById(R.id.buttonRegister);
resetRegisterFields();
progressDialog.dismiss();
displayPid(patient_id);
bt.setEnabled(true);
.
.
});
}

How to search if a username exist in the given firebase database?

{
users:
{
apple:
{
username : apple
email : apple#xy.com
uid : tyutyutyu
}
mango:
{
username : mango
email : mango#xy.com
uid : erererer
}
}
}
This is what I am doing
CREATING USER if checkUsername method returns 0
if(checkFirebaseForUsername(username)==0) {
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(getBaseContext(),"inside",Toast.LENGTH_LONG).show();
User newUser = new User();
newUser.setUserId(mAuth.getCurrentUser().getUid());
newUser.setUsername(username);
newUser.setEmailId(email);
try{
mRef.child("users").child(username).setValue(newUser);
}
catch(Exception e){
Toast.makeText(SignUpActivity.this,"error while inserting",Toast.LENGTH_LONG).show();
}
AlertDialog.Builder builder = new AlertDialog.Builder(SignUpActivity.this);
builder.setTitle(R.string.signup_success)
.setPositiveButton(R.string.login_button_label, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(SignUpActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
});
AlertDialog dialog = builder.create();
dialog.show();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(SignUpActivity.this);
builder.setTitle(R.string.signup_error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
My checkUsername method -
public int checkFirebaseForUsername(String passedUsername){
final int[] flag = {0};
final String myPassedUsername = passedUsername;
Log.e("tag","working now");
//flag[0]=1;
DatabaseReference mTest = FirebaseDatabase.getInstance().getReference();
mTest.child("users").child(passedUsername).addChildEventListener(new ChildEventListener() {
#Override
public void onDataChanged(DataSnapshot dataSnapshot) {
Log.e("tag","checking");
if(dataSnapshot.exists()){
Log.e("tag","exists");
flag[0]=1;
}
}
#Override
public void onCancelled(DataSnapshot datasnapshot){
}
});
if(flag[0]==1)
return 1;
else
return 0;
}
This is how I am inserting users in my firebase-database and I want to check if a username is available for a new user or not.
Therefore I need to check is there any user already registered with that username....Please help I have already tried whatever I could understand after reffering to documentation provided on the official firebase blog but all in vain!!
EDIT: New answer, old one still below.
I would get rid of your method "checkFirebaseForUsername" because it will always return 0, no matter what.
What you need to do is this:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("users").child("username").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
// use "username" already exists
// Let the user know he needs to pick another username.
} else {
// User does not exist. NOW call createUserWithEmailAndPassword
mAuth.createUserWithPassword(...);
// Your previous code here.
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Old Answer:
{
users:
{
apple[X]:
{
username : apple[Y]
email : apple#xy.com
uid : tyutyutyu
}
mango:
{
username : mango
email : mango#xy.com
uid : erererer
}
}
}
If for example, the node apple[X] will always have the same name as the child property "username":apple[Y], then it is as simple as this.
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("users").child("username").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
// use "username" already exists
} else {
// "username" does not exist yet.
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
however, if say, the node apple[X] can have a different value than the property apple[Y], and you want to see if any node exists where the "username" property is the same, then you will need to do a query.
Query query = FirebaseDatabase.getInstance().getReference().child("users").orderByChild("username").equalTo("usernameToCheckIfExists");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getChildrenCount() > 0) {
// 1 or more users exist which have the username property "usernameToCheckIfExists"
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
You may try this.
final String userName = unameEditText.getText().toString();
databaseReference.child("users").orderByChild("username").equalTo(userName).addListenerForSingleValueEvent(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.i(Constants.TAG, "dataSnapshot value = " + dataSnapshot.getValue());
if (dataSnapshot.exists()) {
// User Exists
// Do your stuff here if user already exists
Toast.makeText(getApplicationContext(), "Username already exists. Please try other username.", Toast.LENGTH_SHORT).show();
} else {
// User Not Yet Exists
// Do your stuff here if user not yet exists
}
}
#Override
public void onCancelled (DatabaseError databaseError){
}
}
);
You just check if user is already exits or not by below code:
private DatabaseReference mDatabase;
// ...
mDatabase = FirebaseDatabase.getInstance().getReference();
final String userName = "your_user_name"; // replace with your user name
mDatabase.child("users").child(userName).addListenerForSingleValueEvent(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
// User Exists
// Do your stuff here if user already exits
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "getUser:onCancelled", databaseError.toException());
}
});
You can also see Firebase doc for the same on below link:
Read data once

Categories

Resources