Function addListenerForSingleValueEvent from firebase - android

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

Related

Find data which may be added to the firebase

I am working on an android project where I am using firebase database.
The problem is that i want to check for a particular data which may exist after sometime in the database.
For a clarification, there are two users in firebase, 1) Prem, 2) Suraj. When Prem clicks on a button "Send requests" then Suraj gets Prem's request now if Suraj clicks on that request then the firebase data base makes a child "Playing" which contains - "Prem:Suraj" and now from Prem's side i want to check if Suraj has clicked on that request so i thought it would be best to see if that data exists but its not working because the data will be existing in future and not in the current time.
If anyone could help me, i'll be really grateful.
`//Sender Side
private void confirmRequestTo(final String OtherPlayer) {
AlertDialog.Builder b = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.connecting_players, null);
b.setView(dialogView);
b.setTitle("Start Game?");
b.setMessage("Connect with " + OtherPlayer );
b.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
myRef.child("Users").child(OtherPlayer).child("request").push().setValue(LoginUserID); //Sending the Request
Toast.makeText(Request_InterfaceActivity.this, "Waiting For " + OtherPlayer + " to Join", Toast.LENGTH_SHORT).show();
Request_InterfaceActivity.help = true;
//Waiting for the Request to be Accepted
String pid = UserName + ":" + OtherPlayer;
DatabaseReference playref = myRef.child("Playing");
int sum = 100;
for(int i =0; i<sum;i++) {
playref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (int j = 0; j < sum; j++) {
if (snapshot.hasChild(UserName + ":" + OtherPlayer)) {
StartGame(UserName + ":" + OtherPlayer, OtherPlayer, "TO");
} else {
Toast.makeText(Request_InterfaceActivity.this, UserName + ":" + OtherPlayer, Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Log.d(TAG, error.getMessage());
}
});
}
}
}).setNegativeButton("Back", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Request_InterfaceActivity.help = false;
}
});
b.show();
}
//Receiver Side
private void confirmRequestFrom(final String OtherPlayer) {
AlertDialog.Builder b = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.connecting_players, null);
b.setView(dialogView);
b.setTitle("Start Game?");
b.setMessage("Connect with " + OtherPlayer );
b.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
StartGame(OtherPlayer + ":" + UserName, OtherPlayer, "From");
}
});
b.setNegativeButton("Back", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
b.show();
}
private void StartGame(String PlayerGameID, String OtherPlayer, String requestType) {
//To Implement Later
myRef.child("Playing").child(PlayerGameID).removeValue();
Intent i = new Intent(getApplicationContext(),OnlineGameActivity.class);
i.putExtra("PlayerSession", PlayerGameID);
i.putExtra("Username", UserName);
i.putExtra("OtherPlayer", OtherPlayer);
i.putExtra("LoginUID", LoginUID);
i.putExtra("RequestType", requestType);
startActivity(i);
finish();
myRef.getRoot().child("Users").orderByKey().equalTo(UserName).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for(DataSnapshot postsnapshot :snapshot.getChildren()){
String key = myRef.child("Users").child(UserName).getKey();
myRef.child("Users").child(key).removeValue();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}`

Database not update the value

I am trying to make a social app .. and I want when the user clicks the edit category database should be updated to the new value .. but it is like static not changing to new value .. I don't know the problem in logic or in the code ..
private void showCategoryUpdateDialog(String Key) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("تغيير " + Key);
LinearLayout linearLayout = new LinearLayout(getActivity());
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setPadding(15, 10, 15, 10);
RadioButton radioButton = new RadioButton(getActivity());
radioButton.setText("علمي علوم");
RadioButton radioButton2 = new RadioButton(getActivity());
radioButton2.setText("علمي رياضة");
RadioButton radioButton3 = new RadioButton(getActivity());
radioButton3.setText("أدبي");
linearLayout.addView(radioButton);
linearLayout.addView(radioButton2);
linearLayout.addView(radioButton3);
builder.setView(linearLayout);
builder.setPositiveButton("Update", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String value = radioButton.getText().toString().trim();
String value2 = radioButton2.getText().toString().trim();
String value3 = radioButton3.getText().toString().trim();
if (!TextUtils.isEmpty(value)) {
pd.show();
HashMap<String, Object> result = new HashMap<>();
result.put(Key, value);
databaseReference.child(user.getUid()).updateChildren(result)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
pd.dismiss();
Toast.makeText(getActivity(), "Updated...", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
pd.dismiss();
Toast.makeText(getActivity(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(getActivity(), "Please enter " + Key, Toast.LENGTH_SHORT).show();
}
if (!TextUtils.isEmpty(value2)) {
pd.show();
HashMap<String, Object> result2 = new HashMap<>();
result2.put(Key, value2);
databaseReference.child(user.getUid()).updateChildren(result2)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
pd.dismiss();
Toast.makeText(getActivity(), "Updated...", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
pd.dismiss();
Toast.makeText(getActivity(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(getActivity(), "Please enter " + Key, Toast.LENGTH_SHORT).show();
}
if (!TextUtils.isEmpty(value3)) {
pd.show();
HashMap<String, Object> result3 = new HashMap<>();
result3.put(Key, value3);
databaseReference.child(user.getUid()).updateChildren(result3)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
pd.dismiss();
Toast.makeText(getActivity(), "Updated...", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
pd.dismiss();
Toast.makeText(getActivity(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(getActivity(), "Please enter " + Key, Toast.LENGTH_SHORT).show();
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.create().show();
}
In this picture have more details
Emulator
And this GIF from my Database
https://media.giphy.com/media/ZY36QuzJsdXIhIQh7k/giphy.gif
first: make sure that the new value is stored in the database (from the console)
second: after the update is completed onCompleteListener get the data again.
you can listen for this field changes in real-time which could be better than getting the data after every update.

How to ensure my data is saved on Firebase?

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'

Android ListView update items, Firebase database

I have a code:
#Override
protected void onCreate(Bundle savedInstanceState) {
.........
listViewMyAccountSettings = (ListView) findViewById(R.id.listViewMyAccountSettings);
arrayList = new ArrayList();
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, arrayList);
listViewMyAccountSettings.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
listViewMyAccountSettings.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 0){
showAlertUsername();
} else if (position == 1){
showAlertAge();
}
......................
}
});
.................
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("userdata").child(myEmail).child("username");
myRef.addValueEventListener(new ValueEventListener() {
#SuppressLint("SetTextI18n")
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
username = dataSnapshot.getValue(String.class);
arrayList.add("Your username: " + username);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w("TAG", "Failed to read value.", error.toException());
}
});
There is showAlertUsername method:
private void showAlertUsername() {
alertDialogBuilder = new AlertDialog.Builder(
MyAccountSettings.this);
input = new EditText(MyAccountSettings.this);
lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
alertDialogBuilder.setView(input);
alertDialogBuilder.setPositiveButton("Discard",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
Toast.makeText(getApplicationContext(), "No changes were made",
Toast.LENGTH_SHORT).show();
}
});
alertDialogBuilder
.setTitle("USERNAME")
.setMessage("Enter new username")
.setCancelable(false)
.setNegativeButton("Change",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (!input.getText().toString().isEmpty()) {
mDatabase.child("userdata").child(myEmail).child("username").setValue(input.getText().toString());
Toast.makeText(getApplicationContext(), "Your username was changed successfully",
Toast.LENGTH_LONG).show();
listViewMyAccountSettings.invalidateViews();
} else {
Toast.makeText(getApplicationContext(), "Username can't be empty. No changes were made",
Toast.LENGTH_LONG).show();
}
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
And I want to update particular field in list view when I change value(and set it into database). Problem is that when I change value in database it adds a new item to list view with new value? Is there a way to update the old one without restarting an activity? Thanks.
Every time the firebase data is changed you add a new item to the list:
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
username = dataSnapshot.getValue(String.class);
arrayList.add("Your username: " + username);
}
Clear the list if before that if you want to have a single entry.
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
arrayList.clear();
username = dataSnapshot.getValue(String.class);
arrayList.add("Your username: " + username);
arrayAdapter.notifyDataSetChanged();
}
You would change the data if your current ArrayList contains otherwise just add the new one:
public void onDataChange(DataSnapshot dataSnapshot) {
username = dataSnapshot.getValue(String.class);
String item = "Your username: " + username;
if(arrayList.contains(item)) {
//if current arrayList contains the item just change it
arrayList.set(arrayList.indexOf(item), item);
} else {
//otherwise add the new one
arrayList.add(item);
}
//assuming your data is mutable
arrayAdapter.notifyDataSetChanged();
}
Use ChildEventListener instead of ValueEventListener.ChildEventListener gives the following over methods,
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
// here in dataSnapshot you will the detail for which the value is changed,using this you can update the list.
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {}
#Override
public void onCancelled(DatabaseError databaseError) {}
#Priya thanks a used a piece of your answer, the code now looks this way and it is doing what it should.
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("userdata").child(myEmail);
myRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey) {
if (dataSnapshot.getKey().equals("username")) {
username = (String) dataSnapshot.getValue();
arrayList.add("Username: " + username);
} else if (dataSnapshot.getKey().equals("age")) {
age = (String) dataSnapshot.getValue();
arrayList.add("Age: " + age);
} else if (dataSnapshot.getKey().equals("gender")) {
gender = (String) dataSnapshot.getValue();
arrayList.add("Gender: " + gender);
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String prevChildKey) {
if (dataSnapshot.getKey().equals("username")) {
username = (String) dataSnapshot.getValue();
arrayList.set(2, "Username: " + username);
} else if (dataSnapshot.getKey().equals("age")) {
age = (String) dataSnapshot.getValue();
arrayList.set(0, "Age: " + age);
} else if (dataSnapshot.getKey().equals("gender")) {
gender = (String) dataSnapshot.getValue();
arrayList.set(1, "Gender: " + gender);
}
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String prevChildKey) {}
#Override
public void onCancelled(DatabaseError databaseError) {}
});

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