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
Related
This question already has an answer here:
How to create auto incremented key in Firebase?
(1 answer)
Closed 4 years ago.
I want to append a String to my List on the Firebase Realtime Database.
(My code already works but there is a problem)
So the Database looks like this:
message:
0: "some string"
1: "another string"
2: "some string"
But I think the problem with this code would be, that if somebody reads the numbers of messages and then wants to write a message there would be a problem, when another user writes a message in the mean time (because the number of messages would change).
FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference myRef = database.getReference("message");
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
myRef.child(
String.valueOf(dataSnapshot.getChildrenCount())
).setValue("SOME STRING");
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Trying to use sequential numeric indexes (also often referred to as array indexes or auto-increment values) in a multi-user Firebase is an anti-pattern for a few reasons.
As you've already noted yourself, there's a chance of users overwriting each other's data. This is fixable however by using a transaction, which is the way to go if you need to property a value based on its existing value. The reference documentation for the JavaScript DatabaseReference.transaction method have this example that is pretty much what you need:
// Increment Ada's rank by 1.
var adaRankRef = firebase.database().ref('users/ada/rank');
adaRankRef.transaction(function(currentRank) {
// If users/ada/rank has never been set, currentRank will be `null`.
return currentRank + 1;
});
The syntax in Android is slightly more involved, but would work the same.
While a transaction works, this means that the application will only work when the user is connected to the server. When they're offline, the transaction will fail.
For these reasons Firebase apps typically use a different mechanism to generate their keys. The built-in push() method of the API generates a unique, always-incrementing key. While this key is not as readable as your sequential, numeric keys, they do address both of the above problems without the need for you to write more code for it yourself. With push() adding a message becomes as simple as:
final DatabaseReference myRef = database.getReference("message");
myRef.push().setValue("SOME STRING");
Note that this topic has been covered quite a bit already, so I recommend also checking out:
Best Practices: Arrays in Firebase
The 2^120 Ways to Ensure Unique Identifiers
How to create auto incremented key in Firebase?
Auto-increment a value in Firebase (has the transaction code for Android)
how do i auto increment a value in firebase
This question already has an answer here:
How to create auto incremented key in Firebase?
(1 answer)
Closed 4 years ago.
I want to append a String to my List on the Firebase Realtime Database.
(My code already works but there is a problem)
So the Database looks like this:
message:
0: "some string"
1: "another string"
2: "some string"
But I think the problem with this code would be, that if somebody reads the numbers of messages and then wants to write a message there would be a problem, when another user writes a message in the mean time (because the number of messages would change).
FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference myRef = database.getReference("message");
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
myRef.child(
String.valueOf(dataSnapshot.getChildrenCount())
).setValue("SOME STRING");
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Trying to use sequential numeric indexes (also often referred to as array indexes or auto-increment values) in a multi-user Firebase is an anti-pattern for a few reasons.
As you've already noted yourself, there's a chance of users overwriting each other's data. This is fixable however by using a transaction, which is the way to go if you need to property a value based on its existing value. The reference documentation for the JavaScript DatabaseReference.transaction method have this example that is pretty much what you need:
// Increment Ada's rank by 1.
var adaRankRef = firebase.database().ref('users/ada/rank');
adaRankRef.transaction(function(currentRank) {
// If users/ada/rank has never been set, currentRank will be `null`.
return currentRank + 1;
});
The syntax in Android is slightly more involved, but would work the same.
While a transaction works, this means that the application will only work when the user is connected to the server. When they're offline, the transaction will fail.
For these reasons Firebase apps typically use a different mechanism to generate their keys. The built-in push() method of the API generates a unique, always-incrementing key. While this key is not as readable as your sequential, numeric keys, they do address both of the above problems without the need for you to write more code for it yourself. With push() adding a message becomes as simple as:
final DatabaseReference myRef = database.getReference("message");
myRef.push().setValue("SOME STRING");
Note that this topic has been covered quite a bit already, so I recommend also checking out:
Best Practices: Arrays in Firebase
The 2^120 Ways to Ensure Unique Identifiers
How to create auto incremented key in Firebase?
Auto-increment a value in Firebase (has the transaction code for Android)
how do i auto increment a value in firebase
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.
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
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.