Firebase show if child exists - android

I am using FirebaseIndexRecyclerAdapter and I'am trying to show post for the following users so I have used these method blew but It show posts if the post id is available at the following users:
Here's my json:
"Following" : {
"ORBBKfZAAUhqI1h7ojQDzYOjgkp1" : {
"pypD1SYZkbcYesk09WuMUY1AkTf1": true,
//I need to show this UID posts only but,
//When I add here post id it show the post
//Ex:"-KduqnVVczZf5uibQiZ-" : true,//Post Shows Up
},
"Posts" : {
"-KduqnVVczZf5uibQiZ-" : {
"Describe" : "gg",
"Time" : 14881230655,
"UID" : "pypD1SYZkbcYesk09WuMUY1AkTf1",
"Username" : "Jone",
"Wallpaper" : "https://firebasestorage.googleapis.com/v0/b/test-3f4c5.appspot.com/o/Posts%2Fcropped906285501.jpg?alt=media&token=0c1a3a3d-6e48-4c4e-ba59-f5646bf8965f"
},
"-Ke5gJ00CxbjhOuhzLIx" : {
"Describe" : "hajj",
"Time" : 1488318465,
"UID" : "pypD1SYZkbcYesk09WuMUY1AkTf1",
"Username" : "Dom",
"Wallpaper" : "https://firebasestorage.googleapis.com/v0/b/test-3f4c5.appspot.com/o/Posts%2Fcropped1717103943.jpg?alt=media&token=a85b2488-5ac7-49a7-9ad0-dbf4e6f29389"
},
"-KeCuiFmUCpN19zwsTsR" : {
"Describe" : "a",
"Profile" : "https://lh4.googleusercontent.com/-suB77riNoX8/AAAAAAAAAAI/AAAAAAAAAAA/ADPlhfKMzINn-Ki538Sqf6SRGaXC81-WuQ/s200-c/photo.jpg",
"Time" : 1488439652,
"UID" : "z2SNUlLd6mQM8nnlkU2VUws5Ggl2",
"Username" : "Dom",
"Wallpaper" : "https://firebasestorage.googleapis.com/v0/b/test-3f4c5.appspot.com/o/Posts%2Fcropped1913886685.jpg?alt=media&token=c8ad26b2-8f09-453b-b48a-aad9e4d8b5c3"
},
"-KeD2fBUQ09HVMrvAneb" : {
"Describe" : "ee",
"Profile" : "https://lh4.googleusercontent.com/-suB77riNoX8/AAAAAAAAAAI/AAAAAAAAAAA/ADPlhfKMzINn-Ki538Sqf6SRGaXC81-WuQ/s200-c/photo.jpg",
"Time" : 1488441999,
"UID" : "z2SNUlLd6mQM8nnlkU2VUws5Ggl2",
"Username" : "Dom",
"Wallpaper" : "https://firebasestorage.googleapis.com/v0/b/test-3f4c5.appspot.com/o/Posts%2Fcropped1904338270.jpg?alt=media&token=d200b7fc-15e7-4dc4-9913-59c377929e9e"
},
"-KeDfnMWiB7k_4J3FBgZ" : {
"Describe" : "f12g",
"Time" : 1488452517,
"UID" : "ORBBKfZAAUhqI1h7ojQDzYOjgkp1"
"Username" : "Young",
"Wallpaper" : "https://firebasestorage.googleapis.com/v0/b/test-3f4c5.appspot.com/o/Posts%2Fcropped1872832638.jpg?alt=media&token=80239844-a872-47e2-9689-92d368dd9452"
},
"-KeDfrw4inUQFtIDXJHp" : {
"Describe" : "fg",
"Time" : 1488452536,
"UID" : "ORBBKfZAAUhqI1h7ojQDzYOjgkp1"
"Username" : "Young",
"Wallpaper" : "https://firebasestorage.googleapis.com/v0/b/test-3f4c5.appspot.com/o/Posts%2Fcropped1872832638.jpg?alt=media&token=80239844-a872-47e2-9689-92d368dd9452"
},
}
}
And here's my method that I use:
mAuth = FirebaseAuth.getInstance();
mCurrentUser = mAuth.getCurrentUser();
mDatabase = FirebaseDatabase.getInstance().getReference().child("Posts");
mDatabaseFriends = FirebaseDatabase.getInstance().getReference().child("Following").child(mCurrentUser.getUid());
FirebaseIndexRecyclerAdapter<Getting_Posts,PostViewHolder> firebaseIndexRecyclerAdapter = new FirebaseIndexRecyclerAdapter<Getting_Posts, PostViewHolder>(
Getting_Posts.class,R.layout.post_card_design,PostViewHolder.class,mDatabaseFriends,mDatabase)
{
#Override
protected void populateViewHolder(PostViewHolder viewHolder, Getting_Posts model, int position) {}};

To check if a fiven reference have childrens you should use dataSnapshot.exists() or dataSnapshot.getChildrenCount() > 0 with the given DataSnapshot on your callback.
If you want to retrieve the post which id is equal to the followers you should modify your database adding an extra level to pur Posts table where the post will be already together based on a user id:
"Posts": {
"USER_ID_1": {
"post_id_1": {
"Describe": "gg",
"Time": 14881230655,
"UID": "pypD1SYZkbcYesk09WuMUY1AkTf1",
"Username": "Jone"
},
"post_id_2": {
"Describe": "gg",
"Time": 14881230655,
"UID": "pypD1SYZkbcYesk09WuMUY1AkTf1",
"Username": "Jone"
}
},
"USER_ID_2": {
"post_id_3": {
"Describe": "gg",
"Time": 14881230655,
"UID": "pypD1SYZkbcYesk09WuMUY1AkTf1",
"Username": "Jone"
},
"post_id_4": {
"Describe": "gg",
"Time": 14881230655,
"UID": "pypD1SYZkbcYesk09WuMUY1AkTf1",
"Username": "Jone"
}
}
To iterate looking to get all the posts inside each of your user's(just if you are following the new data model that I post you upside), you can retrieve them doing this:
List<Getting_Posts> totalPosts = new ArrayList<>();
//Check if the dataSnapshot have childrens
if (dataSnapshot.hasChildren()){
//This for iterate for each USER_ID from your database
for (DataSnapshot users : dataSnapshot.getChildren()) {
//This second iterate for each post for each user
for (DataSnapshot posts : users.getChildren()) {
totalPosts.add(dataSnapshot.getValue(Getting_Posts.class));
}
}
}
return totalPosts;
You can read more about this in the next post or in the oficial documentation:
https://www.airpair.com/firebase/posts/structuring-your-firebase-data
https://firebase.google.com/docs/database/web/structure-data?hl=en-419

Related

android: adding a new node

Need to add a new node "Completed" under the parent which will eventually contain all the information from the node "Requests" at end of the ride.
So basically, I need to create node "Completed" first but its not adding it.
database
{
"Requests" : {
"iowpxU6WKUWpzWJyfssSoOVCPFj2" : {
".priority" : "f8118c3k3v",
"destination" : "221 Prince William St",
"details" : {
"driver" : "nYIAHSYimJMHbMkXqDt9PQ0U3Nf2",
"location" : "27 Horsfield St",
"request status" : "accepted",
"ridePrice" : 3.75,
"rideStatus1" : "arrived at pickup",
"rideStatus2" : "rider in vehicle",
"rideStatus3" : "destination bound",
"rideStatus4" : "arrived at destination",
"rider" : "iowpxU6WKUWpzWJyfssSoOVCPFj2",
"riderPaid" : "true"
},
"Users" : {
"Drivers" : {
"nYIAHSYimJMHbMkXqDt9PQ0U3Nf2" : {
"driver" : "nYIAHSYimJMHbMkXqDt9PQ0U3Nf2",
"email" : "driver#me.com",
"name" : "driver",
"password" : "whatever",
"phone" : "5551212",
"rates" : "0"
}
},
"Riders" : {
"iowpxU6WKUWpzWJyfssSoOVCPFj2" : {
"avatarUrl" : "",
"email" : "rider#me.com",
"name" : "rider",
"password" : "whatever",
"phone" : "5551313",
"rates" : "0",
"riderId" : "iowpxU6WKUWpzWJyfssSoOVCPFj2"
}
}
}
}
addNewNode
private void addNewNode() { // TODO: ........ NOT ADDING NEW NODE :-| ..........
Toast.makeText(this, "addNewNode", Toast.LENGTH_LONG).show();
DatabaseReference newNode = FirebaseDatabase.getInstance().getReference("Completed");
newNode.child(riderId).push().addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Toast.makeText(DriverTripDetail.this, "addNewNode: onDataChange", Toast.LENGTH_LONG).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Any assistance on how I can fix this would be greatly appreciated.
The Firebase Database stores values at paths. If there is no value, the path does not exist.
Your code creates a reference to /Completed/$pushID. but doesn't set any value, so the path doesn't get created. Something like this will work, since it sets a value:
newNode.child(riderId).push().setValue(true)

Firebase whitelist and recyclerView

{
"Events" : {
"events" : {
"-KT5UMQAhDHs1bB8bKLc" : {
"activity" : "biking",
"address" : "54°05'45.8\"N 28°19'02.9\"E, просп. Мира 9, Жодино, Беларусь",
"category" : "sport",
"creatorID" : "m11EvlP19OSbEz8XYl2MsNCwGXX2",
"date" : 1475431200689,
"forFriends" : true,
"info" : "вттчтвт",
"name" : "ьаьатвтвтт",
"uid" : "-KT5UMQAhDHs1bB8bKLc"
},
"-KUSsl7RaL-dVoDCoSYT" : {
"activity" : "picnic",
"address" : "Узденский район, Узденский район, Беларусь",
"category" : "entertainment",
"creatorID" : "1RXDSJzSEXakxvNdM41Ae3nbHN72",
"date" : 1477328400000,
"forFriends" : false,
"info" : "45",
"name" : "Test of date",
"uid" : "-KUSsl7RaL-dVoDCoSYT"
}
},
"FriendsOF" : {
"NuKweeGv8zTgt1Vi9RcU3i1u86U2" : {
"1RXDSJzSEXakxvNdM41Ae3nbHN72" : true
},
"m11EvlP19OSbEz8XYl2MsNCwGXX2" : {
"1RXDSJzSEXakxvNdM41Ae3nbHN72" : true
}
},
"Users" : {
"1RXDSJzSEXakxvNdM41Ae3nbHN72" : {
"email" : "*#gmail.com",
"name" : "Алексей Гвоздицкий",
"picture" : "*.jpg"
},
"NuKweeGv8zTgt1Vi9RcU3i1u86U2" : {
"email" : "*#gmail.com",
"name" : "Ольга Гвоздицкая",
"picture" : "*.jpg"
},
"m11EvlP19OSbEz8XYl2MsNCwGXX2" : {
"email" : "*#gmail.com",
"name" : "Егор Александров",
"picture" : "*.jpg"
}
}
}
I have a list of "events". Every "event" can be "forFiends" only (only if current user is in event creators "FriendsOF" list, then he can see this event. FriendsOF it's a whitelist). All availiable for current user events i want to represent in RecyclerView.
I am stucked. I can get all data snapshot and then filter on client side it. But it is not way of Jedi, because i load tonns of unnecessary data. Another solution is to deny acces to event if user should not see it. But i don't understand how to do it. My ref is mEventsRef = FirebaseDatabase.getInstance().getReference().child("Events").child("events"); And rule i can make for
"events":{
"$eventId":{".read":....}
}
So according to this guide i'll get empty recyclerView because of "error callback triggered with PERMISSION_DENIED"
Help me to solve my problem please!

Android Firebase, server side filtering for Recyclerview

Following is my firebase data structure
{
"ticketing" : {
"1476639649079-mahto" : {
"agentId" : 0,
"agent_status" : "1_Dispatched",
"approverId" : 0,
"contractorId" : 0,
"dateTime" : "16-10-2016 13:40 PM",
"priority" : "MEDIUM",
"requester" : {
"issue" : "issue 3",
"location" : "location 3",
"priority" : "Medium",
"shop" : "shop 3",
"site" : "site 3",
"userInfo" : {
"email" : "m#gmail.com",
"firstname" : "mahto",
"isLoggedin" : true,
"lastname" : "pancha",
"loggedin" : true,
"number" : "123123123",
"password" : "q",
"role" : "fieldagent",
"userid" : "2",
"username" : "q"
}
},
"requesterId" : 2,
"status" : "Incoming",
"ticketNumber" : "1476639649079-mahto"
},
"1476741838857-mahto" : {
"agentId" : 1,
"agent_status" : "1_Incoming",
"approverId" : 0,
"contractorId" : 0,
"dateTime" : "17-10-2016 18:03 PM",
"priority" : "HIGH",
"requester" : {
"issue" : "Description 3",
"location" : "Location 3",
"priority" : "HIGH",
"shop" : "shop 3",
"site" : "site 3",
"userInfo" : {
"email" : "m#gmail.com",
"firstname" : "mahto",
"isLoggedin" : true,
"lastname" : "pancha",
"loggedin" : true,
"number" : "123123123",
"password" : "q",
"role" : "fieldagent",
"userid" : "2",
"username" : "q"
}
},
"requesterId" : 2,
"status" : "Incoming",
"ticketNumber" : "1476741838857-mahto"
}
}
}
Database refrence
mDatabase = FirebaseDatabase.getInstance().getReference().child("ticketing");
mDatabase.orderByChild("agent_status").equalTo("1_Incoming");
and attached to recyclerview adapter
mAdapter = new FirebaseRecyclerAdapter<Ticket, AgentTicketHolder>(Ticket.class, R.layout.agent_ticket_cardview, AgentTicketHolder.class, mDatabase) { .. }
My expected result is that i will get only one node i.e 1476741838857-mahto which has agent_status value equal to 1_Incoming.
But i'am getting both the nodes in my recylerview.
When you call filtering methods, the Firebase SDK returns a new object for the resulting query. So you need to capture the reference to that object and pass that into the adapter:
mDatabase = FirebaseDatabase.getInstance().getReference().child("ticketing");
Query query = mDatabase.orderByChild("agent_status").equalTo("1_Incoming");
mAdapter = new FirebaseRecyclerAdapter<Ticket, AgentTicketHolder>
(Ticket.class, R.layout.agent_ticket_cardview, AgentTicketHolder.class, query) { .. }

How to display data that depends on other entity?

Having the following data:
"animals" : {
"a1" : {
"name" : "Dog"
},
"a2" : {
"name" : "Cat"
},
"a3" : {
"name" : "Cow"
}
},
"users" : {
"u1" : {
"favAnimals" : {
"a1" : true,
"a2" : true
},
"name" : "Danilo"
}
}
How can I display for the user, using the FirebaseListAdapter, the complete list of animals, highlighing user's favorite animals?
Is it possible to query and join them, to get a Database Reference that would watch for changes both in "/animals" and "/users/$uid/favAnimals" and return something like:
"animals" : {
"a1" : {
"name" : "Dog",
"fav" : true
},
"a2" : {
"name" : "Cat"
"fav" : true
},
"a3" : {
"name" : "Cow"
}
}

How to use orderByKey() with DataSnapshot?

I am populating a list of programs in a RecyclerView. Now i need to sort the programs by the time added. So i thought of adding a timestamp object to each program.
But i read that the PushID is also generated from a timestamp. So i tried to use the orderByKey(). But i can't figure out that how can i use the query with the userSnapshot?
CODE
public void FetchData() {
ProgramItemList.clear();
mRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot userSnapshot : dataSnapshot.getChildren()) {
for (DataSnapshot programSnapshot : userSnapshot.getChildren()) {
program = programSnapshot.getValue(Program.class);
ProgramItem item = new ProgramItem();
String pushID = programSnapshot.getKey();
item.setID(pushID);
item.setName(program.getTitle());
ProgramItemList.add(item);
}
}
}
mAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
JSON
{
"subscriptions" : {
"han#gmail,com" : {
"-KDnhRwHjssOejrqyenP" : {
"category" : "Strength",
"goal" : "This workout can be done while on the phone!",
"length" : 1,
"title" : "Hello Workouts",
"weeks" : {
"week1" : [ "High Knees", "Jumping Jacks", "Burpees" ]
}
},
"-KDni3TN4NMyGXePyp92" : {
"category" : "Strength",
"goal" : "This workout can be done by a BABUJI",
"length" : 1,
"title" : "Indian Workouts",
"weeks" : {
"week1" : [ "Diamond Pushups", "Jackknives", "Pushups" ]
}
}
},
"obama#gmsil,com" : {
"-KDnfjROKeFAL9wccsxY" : {
"category" : "Mobility",
"goal" : "afternoon body weight workout",
"length" : 1,
"title" : "Afternoon HiiT",
"weeks" : {
"week1" : [ "High Knees", "Squats", "Lunges", "Diamond Push-ups", "Lying Triceps Lifts" ]
}
},
"-KDps90Dn6XtJc6Co00b" : {
"category" : "Strength",
"goal" : "goal",
"length" : 1,
"title" : "title",
"weeks" : {
"week1" : [ "Diamond Pushups", "Spiderman Push-up", "Wide Arm Push-ups", "Burpee Pushups" ]
}
}
}
}
}

Categories

Resources