How to get automatically generated Firebase push ID from Firebase Realtime Database? - java

My app sends every message with a unique id (using push() method) so how can I get this id?
my code to send message :
String messageSenderRef = "Messages/" + messageSenderID + "/" + messageReceiverID;
String messageReceiverRef = "Messages/" + messageReceiverID + "/" + messageSenderID;
DatabaseReference userMessagesKeyRef = reference.child("Messages")
.child(messageSenderID).child(messageReceiverID).push();
String messagePushID = userMessagesKeyRef.getKey();
Map messageTextBody = new HashMap();
messageTextBody.put("message",messageText);
messageTextBody.put("type","text");
messageTextBody.put("to",messageReceiverID);
messageTextBody.put("from",messageSenderID);
messageTextBody.put("time",time);
messageTextBody.put("date",date);
messageTextBody.put("isSeen",false);
messageTextBody.put("messageID",messagePushID);
Map messageBodyDetails = new HashMap();
messageBodyDetails.put(messageSenderRef + "/" + messagePushID,messageTextBody);
messageBodyDetails.put(messageReceiverRef + "/" + messagePushID,messageTextBody);
My Firebase database node:
Firebase Node:

If you want to read the value of messageID field, then you should create a reference that points to the cG6v...PXi1 node and use the following lines of code:
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference messagesRef = db.child("Messages");
DatabaseReference messageReceiverIdRef = messagesRef.child(messageSenderID).child(messageReceiverID);
messageReceiverIdRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
for (DataSnapshot ds : task.getResult().getChildren()) {
String messageId = ds.child("messageID").getValue(String.class);
Log.d("TAG", messageId);
}
} else {
Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
}
}
});
The result in the logcat will be:
-ND-fz....l2krv
...

Related

how to get specific child with spacific attribute ..here is my firebase

Here is my Firebase Realtime Database schema. I want to get passwords and usernames from all employees.
Is there a way to get a specific value of a child in the Realtime Database?
To actually get the user names and passwords from all employees, you have to create a reference that points to the "Employs" node, perform a get() call and attach a listener. So please use the following lines of code:
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference employsRef = db.child("Admin").child("Employs");
employsRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
for (DataSnapshot ds : task.getResult().getChildren()) {
String name = ds.child("name").getValue(String.class);
String password = ds.child("name").getValue(String.class);
Log.d("TAG", name + "/" + password);
}
} else {
Log.d("TAG", task.getException().getMessage()); //Don't ignore potential errors!
}
}
});
The result in the logcat will be:
usman/88568558458

Reading data from Firebase Realtime Database for a specific user

What is the proper way to read data from Firebase Realtime Database? I have created a database "Mybill"s with child bills. In child Bills, I am saving UserId from FirebaseAuth so it should be easy to find bills for a specific user and in userID child, I have a child that I have created using the .push() method and in that, I have data about the bill.
It looks like this:
How should I change my Java code so I can get all the bills saved for a specific user (the user that is currently logged in)
this is my code for now :
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("bills");
Query checkUser = ref.orderByChild("UserId").equalTo(Autentication.GetUser());
// Attach a listener to read the data at our posts reference
checkUser.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String email = dataSnapshot.child("email").getValue(String.class);
String market = dataSnapshot.child("market").getValue(String.class);
String price = dataSnapshot.child("price").getValue(String.class);
String date = dataSnapshot.child("date").getValue(String.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
How should I change my Java code so I can get all the bills saved for a specific user (the user that is currently logged in)
To do that, please use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("bills").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String email = ds .child("email").getValue(String.class);
String market = ds .child("market").getValue(String.class);
String price = ds .child("price").getValue(String.class);
Log.d("TAG", email + "/" + market + "/" + price);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
The "date" cannot be read as a String, as it's an object. So the most appropriate way would be to read it as a Map<String, Object>. In this way, you are getting only the bills that correspond to a specific user (logged-in user).

How do it retrieve User data from this database structure?

I am making an app for a school project. I want that when a student logs in they should see their data (ID, NAME, SESSION, PROGRAM) and when anyone of faculty logs in they should see data in faculty node. They can successfully login, just I don't know how to fetch different data for users belonging to 2 different nodes. I am fairly new to android and Firebase so any clear answer will be much appreciated.
This is my Database Structure:
To solve this, please use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("USERS").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String id = ds.child("ID").getValue(String.class);
String name = ds.child("NAME").getValue(String.class);
String program = ds.child("PROGRAM").getValue(String.class);
String session = ds.child("SESSION").getValue(String.class);
Log.d(TAG, id + " / " + name + " / " + program + " / " + session);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage());
}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
The output in your logcat will be:
02 / SA / MCI / SP17
If you want to get the data from the other node, just change the reference accordingly.

How to edit the data inside the unique id of a child in firebase database?

Trying to implement a read receipt feature in my app...
Posting Data
private void sendMessage() {
String messageText = messageArea.getText().toString();
if (TextUtils.isEmpty(messageText)) {
Toast.makeText(getApplicationContext(), "Can't Send Blank Message", Toast.LENGTH_SHORT).show();
} else {
String message_sender_ref = "Messages/" + MessageSenderId + "/" + MessageRecieverId;
String message_reciver_ref = "Messages/" + MessageRecieverId + "/" + MessageSenderId;
Map messageTextBody = new HashMap<>();
messageTextBody.put("Message", messageText);
messageTextBody.put("Seen", "False");
messageTextBody.put("Type", "Text");
messageTextBody.put("Time", ServerValue.TIMESTAMP);
messageTextBody.put("From", MessageSenderId);
DatabaseReference user_message_key = mDatabaseReference.child("Messages").child(MessageSenderId).child(MessageRecieverId).push();
String message_push_id = user_message_key.getKey();
Map messageBodyDetails = new HashMap();
messageBodyDetails.put(message_sender_ref + "/" + message_push_id, messageTextBody);
messageBodyDetails.put(message_reciver_ref + "/" + message_push_id, messageTextBody);
mDatabaseReference.updateChildren(messageBodyDetails, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (databaseError != null) {
Log.d("Chat_Log", databaseError.getMessage().toString());
}
messageArea.setText("");
}
});
}
}
Now how do i access the "Seen = False" data which is inside a unique ID... i can access it through ValueEventListener but how do i make changes of that? i know only to fetch the data but i want to change the data of it... Can someone help me out please
Tried method
DatabaseReference seenRef = mDatabaseReference.child("Messages").child(MessageSenderId).child(MessageRecieverId).child("Seen");
seenRef.setValue("True");
I tried this above method but it just creates one more hild alongside it and sets its value to true.... someone please help me out... Thanks in advance
Database - https://ibb.co/js3iDd
This method you are trying to use
DatabaseReference seenRef = mDatabaseReference.child("Messages").child(MessageSenderId).child(MessageRecieverId).child("Seen");
seenRef.setValue("True");
is replacing or overwriting your current value at that reference, i would suggest to make a map and use updateChildren to just update the value at the desired reference, also if you need to update multiple values at the same reference, this will save you multiple setValues()
Map<String, Object> update = new HashMap<String,Object>();
update.put("Seen", true);
seenRef.updateChildren(update);
but you can also do the same as you are doing without "" in your setValue() because you want to poot a boolean true or false inside it and you are sending a string "True" to the database , this will create a new key replacing/overwriting that same ref with the value Seen : true
DatabaseReference seenRef = mDatabaseReference.child("Messages").child(MessageSenderId).child(MessageRecieverId).child("Seen");
seenRef.setValue(true);
Please check your seenRef, i just checked your db and i think is missing one more ref
so just change your ref
DatabaseReference seenRef = mDatabaseReference.child("Messages").child(MessageSenderId).child(MessageRecieverId).child(your_push_id_message).child("Seen");
in order to get your_push_id_message you will need to get that push id of the message to do that, first attach a listener to it and getKey()
seenRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
String pushMessage = snapshot.getKey();
dataSnapshot.child(pushMessage).child("Seen").setValue(true);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
You are doing wrong because you are the directly updating value not with message-id which you generating for the message using push()
Here you doing
DatabaseReference seenRef = mDatabaseReference.child("Messages").child(MessageSenderId).child(MessageRecieverId).child("Seen");
seenRef.setValue("True");
But you are not referring message id in which you need to do.
Like bellow
DatabaseReference seenRef = mDatabaseReference.child("Messages").child(MessageSenderId).child(MessageRecieverId).child(Message-Id).child("Seen");
seenRef.setValue("True");

Firebase data retrieve with random keys

I have a firebase data structure for my android app and I want to retrieve the data from random keys generated by push() method which is child of Forum node which is a child of root of the database. Please suggest me a way to do this. Thanks.
To display the values of all the children under Forums node, please use the following lines of code:
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference forumsRef = db.child("Forums");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String name = ds.child("name").getValue(String.class);
String ques = ds.child("ques").getValue(String.class);
String title = ds.child("title").getValue(String.class);
String uid = ds.child("uid").getValue(String.class);
Log.d("TAG", name + " / " + ques + " / " + title + " / " + uid);
}
}
#Override
public void onCancelled(DatabaseError error) {
Log.d("TAG", error.getMessage()); //Never ignore potential errors!
}
};
forumsRef.addListenerForSingleValueEvent(valueEventListener);
You can get all of the children nodes of the parent "Forum" node. Just use getChildren() method. Then just randomly select one of the child node at position index.
DataSnapshot snapshot = dataSnapshot.child("Forums");
Iterable<DataSnapshot> children = snapshot.getChildren();
for (DataSnapshot child: children) {
Object obj = child.getValue(Object.class);
}
first you should write your class model "FormusModel" to store the data from server
you can use this
> >
rootRef.child("Forums").addChildEventListener(new
> ChildEventListener() {
> > #Override
> > public void onChildAdded(DataSnapshot dataSnapshot, String s) {
> > ForumsModel model = dataSnapshot.getValue(FormusModel.class);
//now you can use model.getname();....
> }
Note: you must implemnt another method like onChildCahnge listener

Categories