how to fetch multiple data simultaneously from firebase database - java

Fetch messages method
private void fetchMessages() {
rootRef.child("Messages").child(MessageSenderId).child(MessageRecieverId)
.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Messages messages = dataSnapshot.getValue(Messages.class);
messagesList.add(messages);
messageAdapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
}
Defining Ids
MessageSenderId = mAuth.getCurrentUser().getPhoneNumber();
MessageRecieverId = getIntent().getStringExtra("visit_user_id");
trying to make a basic chat app
Since only the senders id is called in rootref only the messages i send r being displayed in d recyclerview... im unable to receive messages because of this... how can i make it to retrieve recievers id and senders id also at the same time
Database strucutre
{
"Messages" : {
"+918105571584" : {
"+919945342730" : {
"-L58IPCLEeE21vH_-1Ry" : {
"message" : "Hi",
"seen" : false,
"time" : 1518427022478,
"type" : "text"
},
"-L58IU1VIHN0rHaUox3a" : {
"message" : "Hello",
"seen" : false,
"time" : 1518427042257,
"type" : "text"
},
"-L58IYN1GpHPdkWCY7Hn" : {
"message" : "Hi",
"seen" : false,
"time" : 1518427060021,
"type" : "text"
}
}
},
"+919945342730" : {
"+918105571584" : {
"-L58IPCLEeE21vH_-1Ry" : {
"message" : "Hi",
"seen" : false,
"time" : 1518427022478,
"type" : "text"
},
"-L58IU1VIHN0rHaUox3a" : {
"message" : "Hello",
"seen" : false,
"time" : 1518427042257,
"type" : "text"
},
"-L58IYN1GpHPdkWCY7Hn" : {
"message" : "Hi",
"seen" : false,
"time" : 1518427060021,
"type" : "text"
}
}
}
},
"Users" : {
"+918105571584" : {
"Email" : "",
"Name" : "Akash",
"Quote" : "",
"Status" : ""
},
"+919945342730" : {
"Email" : "",
"Name" : "Sav",
"Quote" : "",
"Status" : ""
}
}
}

According to your last comment, I understand that you can display only the messages that correpond to a single user. A user can see only his messages butd not other user messages. To solve this, you need to create chat rooms, in which every user can add messages that can be seen by all chat room members.
So for that, you need to change your database structure. You cannot achieve this, using the actual database.

Related

Read data from Firebase database when I have multiple unique ids

I'm having trouble writing in my database because I have multiple unique ids that I don't know how to access.
I know that for writing I need to use something like this:
DatabaseReference ref=database.getReference().child("Children")
ChildData data = new ChildData(fullName,age);
ref.push().setValue(data);
My database looks like this:
{
"Children" : {
"55hxObZjRLY9PSZxZxGgSTRKzpc2" : {
"-MzUih5e40OsWPF_Dj0q" : {
"age" : "22",
"fullName" : "Cristina "
},
"plays" : {
"-MznnNih5fItYf2usXB4" : {
"centiseconds" : "70",
"currentDate" : "01.04.2022",
"currentHour" : "04:23:30",
"numberOfFails" : "5",
"seconds" : "2"
}
}
}
},
"Data" : {
"id1" : {
"centiseconds" : "70",
"currentDate" : "01.04.2022",
"currentHour" : "04:23:30",
"numberOfFails" : "5",
"seconds" : "2"
}
}
}
I need the "plays" child to be under "fullName" in "-MzUih5e40OsWPF_Dj0q", not as a separated child. How can I access the path without hardcoding it like this ref.child("MzUih5e40OsWPF_Dj0q").child("plays").push().setValue(data)? I will have multiple children in "Children" with different ids, I won't be able to harcode them.
Is there any function that returns the path for the unique id?
Here is the entire function:
public void writeNewData
(String fullName,String age) {
DatabaseReference reference = database.getReference().child("Data");
DatabaseReference ref=myRef.push();
ChildData data = new ChildData(fullName,age);
ref.push().setValue(data);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot ds : snapshot.getChildren()) {
DatabaseReference playRef=ref.child("plays");
DatabaseData databaseData = ds.getValue(DatabaseData.class);
playRef.push().setValue(databaseData);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
Edit: This is my desired schema:
{
"Children" : {
"55hxObZjRLY9PSZxZxGgSTRKzpc2" : {
"-MzUih5e40OsWPF_Dj0q" : {
"age" : "22",
"fullName" : "Cristina ",
"plays" : {
"-MznnNih5fItYf2usXB4" : {
"centiseconds" : "70",
"currentDate" : "01.04.2022",
"currentHour" : "04:23:30",
"numberOfFails" : "5",
"seconds" : "2"
}
}
},
}
},
"Data" : {
"id1" : {
"centiseconds" : "70",
"currentDate" : "01.04.2022",
"currentHour" : "04:23:30",
"numberOfFails" : "5",
"seconds" : "2"
}
}
}
If you want the plays information to be a sibling of the age and fullName properties, then you will need to have a plays field/property in your ChildData class.
You'll need two classes, one to represent a "play" and one to represent a "child". At its minimum these will look like:
public class Play {
public String centiseconds, currentDate, currentHour, numberOfFails, seconds;
}
public class Child {
public String age, fullName;
public Map<String, Play> plays = new HashMap<>();
}
If you read/write this class, you will get plays nested under the child's data.

How can I get all my friends and the current user posts in a Firebase Real Time Database Query?

UPDATE1: I still working on it but I can't solve it, maybe restructuring the database? I'll continue thinking but if someone has an idea it will be great to hear
Well I'm trying to get all current users friends and his own posts in a firebase query but I can't get them, always I tryed I only get one friend posts because the others are overwritten. Let me show you how my data base (JSON) is structured and how I want to display the post in the Android project Activity.
UserRef = FirebaseDatabase.getInstance().getReference().child("Users");
PostRef = FirebaseDatabase.getInstance().getReference().child("Post");
...
...
UserRef.child(currentUserID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
if(dataSnapshot.exists())
{
if(dataSnapshot.hasChild("Friends")){
for(DataSnapshot ds : dataSnapshot.child("Friends").getChildren()){
friendsID = ds.getKey(); //String with friendsID
DisplayAllUserPosts();
}
}...
...
private void DisplayAllUserPosts() {
Query SortPost = PostRef.orderByChild("uid").equalTo(friendsID);
FirebaseRecyclerOptions<Posts> options=new FirebaseRecyclerOptions.Builder<Posts>().setQuery(SortPost,Posts.class).build(); \\Posts class is just for getting data base Post nodes elements
FirebaseRecyclerAdapter<Posts, PostsViewHolder> firebaseRecyclerAdapter=new FirebaseRecyclerAdapter<Posts, PostsViewHolder>(options) {...
My Firebase Real Time Database is structured like this:
{
"Post" : {
"10-04-201918:32:09" : {
"counter" : 0,
"date" : "10-04-2019",
"fullname" : "Xuban Illarramendi",
"postimage" : "XXXX",
"profileimage" : "XXXX",
"status" : "",
"time" : "18:32:09",
"uid" : "FP1YJnlJBpfU5aSZlSAErLODWZl2"
},
"10-04-201921:10:06" : {
"counter" : 0,
"date" : "10-04-2019",
"fullname" : "Ander Lopez",
"postimage" : "XXXX",
"profileimage" : "XXXX",
"status" : "",
"time" : "21:10:06",
"uid" : "8wXFsw1pBRYXBVtChqY1Kqi14dy1"
}
},
"Users" : {
"8wXFsw1pBRYXBVtChqY1Kqi14dy1" : {
"Friends" : {
"FP1YJnlJBpfU5aSZlSAErLODWZl2" : {
"date" : "10-04-2019"
},
"sWQGtchFE1fvuSIfPb42ZIWVkbU2" : {
"date" : "10-04-2019"
}
},
"country" : "Spain",
"dob" : "none",
"fullname" : "Ander Lopez",
"gender" : "none",
"profileimage" : "XXXX",
"relationshipstatus" : "none",
"status" : "",
"username" : "anderlopz"
},
"FP1YJnlJBpfU5aSZlSAErLODWZl2" : {
"Friends" : {
"8wXFsw1pBRYXBVtChqY1Kqi14dy1" : {
"date" : "10-04-2019"
},
"sWQGtchFE1fvuSIfPb42ZIWVkbU2" : {
"date" : "10-04-2019"
}
},
"country" : "Spain",
"dob" : "none",
"fullname" : "Xuban Illarramendi",
"gender" : "none",
"profileimage" : "XXXX",
"relationshipstatus" : "none",
"status" : "",
"username" : "xuban"
},
"sWQGtchFE1fvuSIfPb42ZIWVkbU2" : {
"Friends" : {
"8wXFsw1pBRYXBVtChqY1Kqi14dy1" : {
"date" : "10-04-2019"
},
"FP1YJnlJBpfU5aSZlSAErLODWZl2" : {
"date" : "10-04-2019"
}
},
"country" : "Spain",
"dob" : "none",
"fullname" : "Unai Lopez",
"gender" : "none",
"profileimage" : "XXXX",
"relationshipstatus" : "none",
"status" : "",
"username" : "unailopz"
}
}
}
So my real problem is that he displays only the last friend posts, how can I make a query that contains all my friendsID without overwritting the previous friendsID?

Search for child values within two dates in Firebase android

This is how the json looks like
"Node" : {
"1-5-2018" : {
"10001" : {
"centre" : "centre_1",
"name" : "name_1",
"paidAmt" : "25000"
},
"10002" : {
"centre" : "centre_2",
"name" : "name_2",
"paidAmt" : "25000"
},
"10003" : {
"centre" : "centre_3",
"name" : "name_3",
"paidAmt" : "10000"
}
},
"2-5-2018 : {
"10004" : {
"centre" : "centre_4",
"name" : "name_4",
"paidAmt" : "20000"
}
}
I want to retrieve the values(centre, name and paidAmt) inside the given dates
I've tried using this particular query but it always shows data does not exist
Query query = databaseReference1.orderByKey().startAt(fromDate.getText().toString()).endAt(toDate.getText().toString());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
Log.d(TAG, "Data exists within dates");
for(DataSnapshot ds : dataSnapshot.getChildren()) {
Log.d(TAG , "Data are " + ds.getValue().toString());
}
}
else {
Log.d(TAG, "Data does not exist within dates");
}
}
Please let me know if it's possible to retrieve all the data within dates. In future i'm planning to add multiple data inside different dates and want to retrieve them based on requirement. Maybe monthly or weekly.
You are using timestamp instead of a date it may look like this.
"Node" : {
"1525188857" : {
"10001" : {
"centre" : "centre_1",
"name" : "name_1",
"paidAmt" : "25000"
},
"10002" : {
"centre" : "centre_2",
"name" : "name_2",
"paidAmt" : "25000"
},
"10003" : {
"centre" : "centre_3",
"name" : "name_3",
"paidAmt" : "10000"
}
},
"1525188873" : {
"10004" : {
"centre" : "centre_4",
"name" : "name_4",
"paidAmt" : "20000"
}
}

Check if user exists in Firebase database across multiple children nodes

I've a database like this
"Node" : {
"Location_1" : {
"ID1" : {
"address" : "address1",
"balance" : "20",
"batch" : "xyz",
.
.
.
"studentID" : "ID1",
"studentName" : "Username",
"total" : "amount"
}
},
"Location_2" : {
"ID2" : {
"address" : "address2",
"balance" : "0",
"batch" : "xyz",
.
.
"studentID" : "ID2",
"studentName" : "username",
"total" : "amount"
}
}
"Location_3" : {
"ID3" : {
"address" : "address3",
"balance" : "0",
"batch" : "xyz",
.
.
"studentID" : "ID3",
"studentName" : "username",
"total" : "amount"
}
}
I'm able to check if the ID1 exists in a particular Location_1 using the code given below, but I'm unable to find if the ID1 exists across different Location_X id's.
String url = "https://firebaseURL/Node/";
url = url + Location_1;
databaseReference = FirebaseDatabase.getInstance().getReferenceFromUrl(url);
databaseReference.child(ID1).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
Toast.makeText(getApplicationContext(), "ID already present. Enter unique ID!", Toast.LENGTH_SHORT).show();
}
else { // not present, so go ahead and add
}
I tried using a function like this to check if the user is present in all the subNodes.
private boolean checkIfUserExists(String ID) {
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("Location_1");
.
.
String url = "https://firebaseURL/Node/";
databaseReference = FirebaseDatabase.getInstance().getReferenceFromUrl(url);
for(String s: arrayList){
if(getUserExists())
break;
databaseReference.child(s).child(ID).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
setUserExists(true);
}
}
But always the function getUserExists return false. So I end up adding a new user in different location or updating the user's info in the same location.
Please let me know how to proceed on checking the existence of the userID in all the locationIDs

Android Firebase db datasnapshot pulling information from wrong db directory

In my Android app I am using Google Firebase to store information in the database.
I need to iterate through the information, and below for-loop is being used
public void showDataLobReq(DataSnapshot dataSnapshot){
for(DataSnapshot ds : dataSnapshot.child("Lobby_Requests").getChildren()){
System.out.println("asdfasdfasdfasdfasdf"+ds.getValue());
game = ds.child(userID).child("game").getValue(String.class);
console = ds.child(userID).child("console").getValue(String.class);
mic = ds.child(userID).child("mic").getValue(String.class);
players = ds.child(userID).child("players").getValue(String.class);
}
}
You may notice that I put '.child("Lobby_Requests")' after dataSnapshot. this is because the dataSnapshot takes a snapshot of the whole database, so I must go into the subdirectory "Lobby_Requests" because that is where the information I need to iterate through is.
Putting this '.child()' in is being problematic.
I print to the console what the dataSnapshot contains in the first line of the for loop and with .child("Lobby_Requests") it is pulling information from the directory "Lobbies" in the actual database, which is a completely different directory.
Yet, when I remove the '.child()' completely it gives me a view of the whole database like it should. Why is it doing this?
Code for listener:
nRef = mFirebaseDatabase.getReference();
nRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
showDataLobReq(dataSnapshot);
} else {
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Here is JSON:
{
"Games" : {
"Forza 6" : {
"Consoles" : {
"PC" : true,
"Xbox 1" : true,
"Xbox 360" : true
},
"FilePathName" : "forza6",
"Genres" : {
"Racing" : true
},
"Live Lobbies" : 0,
"Name" : "Forza 6"
},
"Minecraft" : {
"Consoles" : {
"PC" : true,
"Xbox 1" : true,
"Xbox 360" : true
},
"FilePathName" : "minecraft",
"Genres" : {
"Adventure" : true,
"Creation" : true,
"Open World" : true
},
"Live Lobbies" : 0,
"Name" : "Minecraft"
}
},
"Lobbies" : {
"Cd6lVd2XMUYoLH6b0xoHsrfXMud2" : {
"Messages" : {
"-Kq6-1HsMvElEXZZyCIk" : {
"messageText" : "hey",
"messageTime" : 1501208519771,
"messageUser" : ""
}
},
"console" : "Origin",
"game" : "Minecraft",
"leader" : "Cd6lVd2XMUYoLH6b0xoHsrfXMud2",
"mic" : "Mic",
"note" : "2345",
"players" : "4"
},
"KUWH5f1TmYfO1O1wgCJLli3XZFi2" : {
"console" : "Steam",
"game" : "Forza 6",
"mic" : "No Mic",
"note" : "Hey Join Here!",
"players" : "2"
},
"hpWkq0D8clPReUetOq9Xtmc4V582" : {
"Messages" : {
"-Kq5a0kX305lFCRTSM_G" : {
"messageText" : "hello",
"messageTime" : 1501201701014,
"messageUser" : ""
},
"-Kq5asufOWQwtmyNJrQ7" : {
"messageText" : "hey",
"messageTime" : 1501201926941,
"messageUser" : ""
}
},
"console" : "Xbox One",
"game" : "Minecraft",
"leader" : "hpWkq0D8clPReUetOq9Xtmc4V582",
"mic" : "Mic",
"note" : "kjhg",
"players" : "4"
}
},
"Lobby_Requests" : {
"Cd6lVd2XMUYoLH6b0xoHsrfXMud2" : {
"Cd6lVd2XMUYoLH6b0xoHsrfXMud2" : {
"console" : "Xbox One",
"game" : "Forza 6",
"mic" : "Mic",
"players" : "5"
}
},
"KUWH5f1TmYfO1O1wgCJLli3XZFi2" : {
"KUWH5f1TmYfO1O1wgCJLli3XZFi2" : {
"console" : "Steam",
"game" : "Forza 6",
"mic" : "No Mic",
"players" : "2"
}
},
"hpWkq0D8clPReUetOq9Xtmc4V582" : {
"hpWkq0D8clPReUetOq9Xtmc4V582" : {
"console" : "Xbox One",
"game" : "Minecraft",
"mic" : "Mic",
"players" : "4"
},
"players" : "4"
}
},
"users" : {
"8cHrNCybwjO3PIUKxyOLiAqxJBv1" : {
"gamertag" : "thedylan",
"uname" : "thedood"
},
"Cd6lVd2XMUYoLH6b0xoHsrfXMud2" : {
"gamertag" : "dmdylan",
"uname" : "ninja goat"
},
"KUWH5f1TmYfO1O1wgCJLli3XZFi2" : {
"gamertag" : "skaner",
"uname" : "asdf"
},
"YvYEIiCBUSYKTviVyWpLHdyDIFw1" : {
"gamertag" : "joejoe",
"uname" : "Jifflingly"
},
"ZmX9yIZ6MNguQa1S3MaYNcxfK2b2" : {
"gamertag" : "dmkaner",
"uname" : "dmkaner"
},
"hpWkq0D8clPReUetOq9Xtmc4V582" : {
"gamertag" : "dmkaner",
"uname" : "dmkaner"
},
"t21ncnuRmeV4F7RknETBisMrxS42" : {
"gamertag" : "asdf",
"uname" : "asdf"
}
}
}
The problem in your code is that you are pushing your data twice and there is no need for this.
"Lobby_Requests" : {
"Cd6lVd2XMUYoLH6b0xoHsrfXMud2" : {
"Cd6lVd2XMUYoLH6b0xoHsrfXMud2" : { //This is wrong
If you'll change the way in which you add data to the Firebase database by pushing that data only once, your code will work for fine. Your database should look like this:
"Lobby_Requests" : {
"Cd6lVd2XMUYoLH6b0xoHsrfXMud2" : {
"console" : "Xbox One",
"game" : "Forza 6",
"mic" : "Mic",
"players" : "5"
},
As you probably see, there is only one pushed key.

Categories