Firebase Android, get only one key value pair - android

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.

Related

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

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

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.

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?

Retriving Data From Firebase In DataSnapshot ( Not In Sequence )

I saved the data into Fire base but when I retrieve it. The data is not in the sequence.
Here Data Is Saved In Accurate Sequence:
But when I retrieve data lost its sequence:
Here is my code for retrieving Data
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Users").child(Autho_User.getUid()).child("Data");
ref.addListenerForSingleValueEvent(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
System.out.println(" Value = "+dataSnapshot.toString());
}
(Printed it just to check values) Data is not in the sequence even I get it through
dataSnapshot.getvalue();
Hope so you got my question. I need the data in sequence
Firebase stores JSON data. By definition the children under a node in JSON are unordered. It is only when the data is displayed or retrieved that it gets an order. So the first screenshot that you show is just the order in which the Firebase Database console display it.
If you want to get the data in a specific order in your application, you need to do two things:
Execute a query that returns the data in that order.
Ensure that your code maintains that order.
The code you shared does neither 1 nor 2, so the order in which the data is printed is anybody's guess. Usually it will be in lexicographical order of the keys, but it is undefined.
To learn how to order/filter data, read the Firebase documentation on ordering and filtering. To learn how to maintain the order of items when you use a ValueEventListener, read the Firebase documentation on listening for value events. When you combine these two, you get:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Users").child(Autho_User.getUid()).child("Data");
Query dataOrderedByKey = ref.orderByKey();
dataOrderedByKey.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
System.out.println("Key = "+childSnapshot.getKey()+" Value = "+childSnapshot.toString());
}
}
...
This is an incredibly common mistake/question, so here are some previous questions for reference:
How to Convert Firebase data to Java Object...?
Ordering of data with Firebase Android
Firebase returning keys of child node in different orders on different devices/Android versions
How to sort by children key value in firebase?
Firebase .getvalue not in the same order as database
Order by date in negative timestamp is not working in Firebase

How to get data from Real-Time Database in Firebase

I've used the Real-Time Database with this setup:
->users
->uid
->name
->email
->other info
If I wanted to save the user data I would use my User class and then set the object in the database like this:
//assume variables have already been declared...
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseUser = mFirebaseAuth.getCurrentUser();
User user = new User(name, email, other values...);
mDBRef.child("users").child(mFirebaseUser.getUid()).setValue(user);
I tried it and it works fine.
But how can I retrieve these values from the database? For instance, once I set a User object as shown above, I may want to retrieve the user's email. I don't mean getting the email through the sign-in provider. I want the email through the real-time database. I've tried working this out for a while now but the documentation isn't helping much. All it shows is to setup listeners in order to wait for changes to the data. But I'm not waiting for changes, I don't want a listener. I want to directly get the values in the database by using the keys in the JSON tree. Is this possible via the real-time database? If so, how can it be done because either the documentation doesn't explain it or I'm just not understanding it. If not possible, am I supposed to be using the Storage database or something else? Thanks.
Firebase uses listeners to get data. That is just the nature of how it works. Although, you can use a single event listener (the equivalent of just grabbing the data once). It will fire immediately and get the data, and will not fire ever again. Here's a code example to get the current user's email:
//Get User ID
final String userId = getUid();
//Single event listener
mDatabase.child("users").child(userId).addListenerForSingleValueEvent(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get user value
User user = dataSnapshot.getValue(User.class);
//user.email now has your email value
}
});

Categories

Resources