Unable to retrieve Friend Key by his email Using FIrebase Realtime Database - android

Database like this
Users
+oagnpangnangpadngn
+psdpgpsdnpgndpsngpndap
+pdgpjdpsgpdsjpgjpsdjpg
--letssupposemyfriendkey <----- I want this key
--name Ahsan
--email test#gmail.com
Now As you can see there is 2 child in each User.
I have already setup an on click button who get the email from layout when I input it in Edit Text. So mainly I want use that email I inputted to get User Key of that email .
e.g I inputted ----> test#gmail.com
Now how do I search users for this email and then get the key of user who has this email?
I am not Using Firestore or Cloud Functions, so if possible don't give me answers for that Im using Firebase Realtime Database in Android Studio using Java (Not Kotlin).

What you're trying to do requires the use of a database query. For example, here is how to find all users with a given ``email` value:
DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference("Users");
Query friendQuery = usersRef.orderByChild("email").equalTo("test#gmail.com");
friendQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot friendSnapshot: dataSnapshot.getChildren()) {
System.out.println(friendSnapshot.getKey()); // letssupposemyfriendkey
System.out.println(friendSnapshot.child("name").getValue(String.class)); // Ahsan
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
}
I highly recommend spending some time in the Firebase documentation on sorting and filtering, taking the Firebase codelab for Android developers, and reading previous questions about Firebase queries.

Related

SQL Query to Firebase query

The SQL query that I want to apply is:
SELECT time FROM Appointment WHERE date = "3/15/2019" AND time = "9:00AM"
but I don't know how to translate it in Firebase. I am using Firebase in Android Studio. My goal here is to prevent date and time duplicate since the app that I'm developing is an online appointment.
Database:
Appointment
angelcrist
aptype: "Objective(Computerized)"
date: "3/15/2019"
name: "Hephep Horray"
time: "9:00AM"
miriammejia
aptype: "Objective(Computerized)"
date: "3/5/2019"
name: "Romz Ysmael"
time: "9:00AM"
There is no way you can do this with the Firebase realtime database. It does not have the capability to perform filtering on multiple conditions. If you have a SQL background, I can say that there are no "multiple where clauses" in Firebase. If you want to check for matches on multiple properties, you'll have to create a composite field as explained in my answer from the following post:
How to sort Firebase records by two fields (Android)
If you consider at some point to try using Cloud Firestore, please note it allows you to filter on multiple conditions. Chaning multiple whereTo calls are working perfectly fine.
First fetch your Appointment data for that particular date using below query, and loop through dataSnapshot childrens to check if you have the time available for that date.
reference.orderByChild('date').equalTo("<yourDate>")
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snap: dataSnapshot.getChildren()) {
//Check for time here
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

how do i change data by custom key in firebase?

I am having an app which writes in firebase and I want my another app with admin privileges to read and edit the data present in the custom key
If this is the picture assume where a random key a my key and I want to edit the data or add new data with the present data in that particular custom key.
Any help will be appreciated
Not 100% sure what you're asking, but if you want to get all the children, do:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("yourTable");
ref.addListenerForSingleValueEvent(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// All your data is in dataSnapshot
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
}
);
If you want to set a specific child's value by the key do:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("yourTable");
ref.child("mySpecificChildId").child("message").setValue("new value");
If these don't help, please add a more specific question!
If these keys are auto generated and you cannot get a hold of them, it does not matter what privligies you have you cannot get them.
However, if you do have the key, or getting it from a function, and you want to change the values at the specific node or just read them you can just query the database for that key and change it after wards something like this:
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference mRef = database.getReference().child("YOUR KEY");
and then you can access read and edit the values at the node
mRef.child("message") //Do Whatever you want
PS: just make sure you are checking if the dataSnapshot Exits!
EDIT:
if your first app is the one generating the keys, you can store them in a different node and access that node based on position to get the key and after you make sure you accessed that node just query for the key

Retrieve and check whether a particular user enter email is present in firebase

I am developing an android application and using Firebase to store my data. I want to query the firebase instance to check whether the user entered email address matches one of the email in Firebase. Attaching the Firebase backend data.
My requirement is, I want to loop through the "guardians", which is the direct child of the Database instance and check whether the user entered email matches any one of the email address in that child. In the attached image, if the user entered email matches either "ram#gmail.com" or the other one, I want to do something.
databaseReference = FirebaseDatabase.getInstance().getReference().child("guardians");
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot data: dataSnapshot.getChildren()){
if (**I am unable to figure out how to search through entire guardians child for the email**) {
} else {
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I am unable to figure out how to search through the entire guardians child to see whether the email matches the user entered email. Any help is appreciated. Thanks in advance.
If you made your current approach work (it's a matter of adding the correct if statement) you'd be downloading the entire list of users, just to check if a specific email address is in use. This is incredibly wasteful of bandwidth, especially as your user list grows.
You should instead use a Firebase Database query to only return the user with the requested email address:
databaseReference = FirebaseDatabase.getInstance().getReference().child("guardians");
Query query = databaseReference.orderByChild("guardianEmail").equalTo("guardian#example.com");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
... the email address is already in use
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
Be sure to add an index for the guardianEmail field, as otherwise you'll still end up downloading all data for the query.
Note that this topic has been covered quite a few times before, and there are better ways to do this check. Most of these involve creating a so-called inverted index, where you use the (encoded) email address of the user as the key. With that structure you can prevent duplicates in Firebase's server-side security rules, which is even more efficient.
For more on this and other approaches, see:
Enforcing unique usernames with Firebase simplelogin
Firebase android : make username unique
How do you prevent duplicate user properties in Firebase?
Usernames with Firebase Simple Login (email/password)
What Firebase rule will prevent duplicates in a collection based on other fields?

Firebase Database select by inner field

I have some difficulties building a query for selecting data in firebase database.
My database structure is like this:
I need to get all users which have contact ghopper. Here the result is alovelace and eclarke. But I really have no idea how to do this simple query in Java.
Thank you for your help!
You'd use Firebase Database queries for that:
DatabaseReference usersRef = FirebaseDatabase.getInstance().ref("users");
Query query = usersRef.orderByChild("contacts/ghopper").equalTo(true);
// My top posts by number of stars
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
System.out.println(snapshot.getKey());
}
}
But this requires that you define an index for each user, which doesn't scale. That is because the structure you have now is meant to allow to easily determine the users for a chat room, and you're trying the opposite.
To efficiently allow getting the chat rooms for a user, you should structure your data so that it also keep a list of users for each chat room. This is often called a secondary/reversed/inverted index.
For more examples of this see:
Firebase query if child of child contains a value
my answer on modeling many-to-many relationship in AskFirebase

Firebase Android, get only one key value pair

I am using Firebase Database in Android. In my app there are three type of users. one of them is "Driver" as shown in json tree below, I want that when user sign in, it automatically gets the value from key value pair "Role" so that I can start the respective activity. is there any easy way to do it or any way to do it?
Assuming you have checked that user is logged in (by Firebase Authentication) and random key child of Driver Information is user uid, then it should be like this:
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
FirebaseDatabase.getInstance().getReference("Driver Information/" + user.getUid() + "/Role")
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String role = dataSnapshot.getValue(String.class);
// do someting with role
}
...
});
Note: replace addValueEventListener with addListenerForSingleValueEvent if you want to get the data one time only and don't mind if that data get changed.

Categories

Resources