I am trying to post data on a particular structure in firebase database but not able to get the expected result. Need the structure like:
ABC->DEVICE_ID-COORDINATES->DATE->PUSHKEY (EX:-KSHJDWFQ)->NOW CHILD LATITUDE AND LONGITUDE.
I am not able to push the child to date as the expected pattern.
Expected pattern:
{
"ABC" : {
"1_861645036247906" : { ///device id
"co-ordinates" : { ///coordinates
"15-11-2017" : { ///date
"KSHJDWFQ" : { ///push key
"latitude" : 4564564,
"longitude" : 45454545
},
"khgjhkhjk" : {
"latitude" : 456456456,
"longitude" : 435345345
}
},
"16-11-2017" : {
"KSHJDWFQ" : {
"latitude" : 4564564,
"longitude" : 45454545
},
"khgjhkhjk" : {
"latitude" : 456456456,
"longitude" : 435345345
}
}
},
"driver_details" : {
"driver_id" : 1,
"driver_name" : "avik"
}
}
},
}
My result is coming like this:
{
"ABC" : {
"2_861645036247906" : {
"-Kz8lFh9B86pCj62gcN3" : {
"coordinates" : {
"17-11-2017" : {
"latitude" : "22.5735875",
"longitude" : "88.431699"
}
}
},
"-Kz8ldboHvGS5QabIVZY" : {
"coordinates" : {
"17-11-2017" : {
"latitude" : "22.5735875",
"longitude" : "88.431699"
}
}
}
}
}
}
This is the code I have done:
Driver driver = new Driver();
String child_node = KPUtils.get_driver_IdPreference(mContext) + "_" + KPUtils.getdeviceid(mContext);
Firebase ref = new Firebase("https://pool------").child(child_node);
String date = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
Map<String, String> m_coordinates = new HashMap<>();
m_coordinates.put("latitude", st_latitude);
m_coordinates.put("longitude", st_longitude);
Map<String, Map<String, String>> gens = new HashMap<>();
gens.put(date, m_coordinates);
Map<String, String> m_driverdetails = new HashMap<>();
m_driverdetails.put("driver_id", "1");
m_driverdetails.put("driver_name", "Avik");
driver.setCoordinates(gens);
//driver.setDriver_details(m_driverdetails);
ref.push().setValue(driver);
You may try this...
ref.child("abc")
.child("device id")
.child("coordinates")
.child(date)
.push()
.setValue(m_coordinates);
Related
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)
I am trying to create chat app with Firebase database. I'm reading docs and watching tutorials but there is one thing I could not figure out how to do. When user sends message to another user, creating a chat room with key: "senderUserId_receiverUserId" You can see my structure below.
{
"chat_rooms" : {
"nTAHqCTmLRcLOM8CTfnHF4lRjLf2_oTLYaHMOMibh3ZqOcmpcWDtSCKp1" : {
"-KtQEGK38lhZrgnNxmqb" : {
"date" : "07/09/2017 10:28",
"message" : “Thanks for helping !”,
"photoUrl" : "http://www.clker.com/cliparts/B/R/Y/m/P/e/blank-profile-hi.png",
"receiverName" : "Ali”,
"receiverUid" : "oTLYaHMOMibh3ZqOcmpcWDtSCKp1",
"senderName" : “John”,
"senderUid" : "nTAHqCTmLRcLOM8CTfnHF4lRjLf2"
},
"-KtQEKK2BmIMzwruN-21" : {
"date" : "07/09/2017 10:28",
"message" : “Another Test Message“,
"photoUrl" : "http://www.clker.com/cliparts/B/R/Y/m/P/e/blank-profile-hi.png",
"receiverName" : “John”,
"receiverUid" : "nTAHqCTmLRcLOM8CTfnHF4lRjLf2",
"senderName" : "Ali",
"senderUid" : "oTLYaHMOMibh3ZqOcmpcWDtSCKp1"
},
"-KtQIGDk5zE4JZuE9pIQ" : {
"date" : "07/09/2017 10:45",
"message" : “Test message !“,
"photoUrl" : "http://www.clker.com/cliparts/B/R/Y/m/P/e/blank-profile-hi.png",
"receiverName" : “John”,
"receiverUid" : "nTAHqCTmLRcLOM8CTfnHF4lRjLf2",
"senderName" : "Ali",
"senderUid" : "oTLYaHMOMibh3ZqOcmpcWDtSCKp1"
}
}
},
"users" : {
"nTAHqCTmLRcLOM8CTfnHF4lRjLf2" : {
"address" : “istanbul”,
"cell_phone" : “none”,
"email" : “john#gmail.com",
"home_phone" : “none”,
"name" : “John”,
"photoUrl" : "http://www.clker.com/cliparts/B/R/Y/m/P/e/blank-profile-hi.png",
"userId" : "nTAHqCTmLRcLOM8CTfnHF4lRjLf2"
},
"oTLYaHMOMibh3ZqOcmpcWDtSCKp1" : {
"address" : “istanbul”,
"cell_phone" : “none”,
"email" : "ali#gmail.com”,
"home_phone" : “none”,
"name" : "Ali",
"photoUrl" : "http://www.clker.com/cliparts/B/R/Y/m/P/e/blank-profile-hi.png",
"userId" : "oTLYaHMOMibh3ZqOcmpcWDtSCKp1"
}
}
}
With this way everything works fine but I don't know how to list user's all conversations at list like WhatsApp's Chats page. I mean when user clicks the conversations item, related conversation will be open.
I'm sending private messages with code below:
public void sendMessageToFirebaseUser(final Context context, final ChatMessageModel chat, final String receiverFirebaseToken) {
final String room_type_1 = chat.getSenderUid() + "_" + chat.getReceiverUid();
final String room_type_2 = chat.getReceiverUid() + "_" + chat.getSenderUid();
final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
databaseReference.child(Constants.ARG_CHAT_ROOMS)
.getRef()
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild(room_type_1)) {
Log.e("aaa", "sendMessageToFirebaseUser: " + room_type_1 + " exists");
databaseReference.child(Constants.ARG_CHAT_ROOMS)
.child(room_type_1)
.push()
.setValue(chat);
} else if (dataSnapshot.hasChild(room_type_2)) {
Log.e("aaa", "sendMessageToFirebaseUser: " + room_type_2 + " exists");
databaseReference.child(Constants.ARG_CHAT_ROOMS)
.child(room_type_2)
.push()
.setValue(chat);
} else {
Log.e("aaa", "sendMessageToFirebaseUser: success");
databaseReference.child(Constants.ARG_CHAT_ROOMS)
.child(room_type_1)
.push()
.setValue(chat);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Thank you for reading my post.
If you want to show a list of chat rooms for the current user, you should model your data to allow that. The easiest way to do this is to add a list of chat rooms for each user to your data model:
"userChatrooms" : {
"nTAHqCTmLRcLOM8CTfnHF4lRjLf2" : {
"nTAHqCTmLRcLOM8CTfnHF4lRjLf2_oTLYaHMOMibh3ZqOcmpcWDtSCKp1": true
},
"oTLYaHMOMibh3ZqOcmpcWDtSCKp1" : {
"nTAHqCTmLRcLOM8CTfnHF4lRjLf2_oTLYaHMOMibh3ZqOcmpcWDtSCKp1": true
}
}
In my Firebase, I have a database for an app. Let's say this is my Firebase JSON:
{
"Users" :{
"User1":{
"City": "Genk"
}
,"User2":{
"City": "Hasselt"
}
,"User3":{
"City": "Genk"
}
,"User4":{
"City": "As"
}
,"User5":{
"City": "Genk"
}
}
}
Now what I want is an ArrayList with all the users with city Genk. How is this possible? I want to use this ArrayList to put the specific Users who live in the city Genk in a ListView.
I suggest you create another child from the root like "UsersCity", In that way you can just call this child and retrieve it to your listview. Here's what i did:
String key = mDatabase.child("post").push().getKey();
UserPost userPost = new UserPost(author,uid,setemoticon,postData,mDate,latlng);
Map<String, Object> postValues = userPost.toMap();
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put("/post/" + key,postValues);
childUpdates.put("/user-post/" + uid + "/" + key, postValues);
mDatabase.updateChildren(childUpdates);
Here's the Json output for that :
{
"post" : {
"-KcGVPpS9CTWPNax61wf" : {
"authorName" : "Test 1",
"dateCreated" : {
"dateCreated" : 1486352395887
},
"postDescription" : "sample post",
"postEmotion" : 2130837658,
"userId" : "KTcgauWoJugXUsq6TAgrdqUvVYm1"
}
},
"user-post" : {
"KTcgauWoJugXUsq6TAgrdqUvVYm1" : {
"-KcGVPpS9CTWPNax61wf" : {
"authorName" : "Test 1",
"dateCreated" : {
"dateCreated" : 1486352395887
},
"postDescription" : "sample post",
"postEmotion" : 2130837658,
"userId" : "KTcgauWoJugXUsq6TAgrdqUvVYm1"
}
}
},
//This child node is for users where you'll want to get the $uid to use for creation of other child nodes.
"users" : {
"KTcgauWoJugXUsq6TAgrdqUvVYm1" : {
"fullname" : "Test 1"
}
}
}
I am just a newbie programmer and I know my answer is not the best but I hope it could help you out with your problem. :)
just fetch specific node data and its working perfect for me
mFirebaseInstance.getReference("yourNodeName").getRef().addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Log.e(TAG, "======="+postSnapshot.child("email").getValue());
Log.e(TAG, "======="+postSnapshot.child("name").getValue());
}
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.e(TAG, "Failed to read app title value.", error.toException());
}
});
I cannot update one field on firebase, when i do delete all the others fields of the database
CODE
String URL_EVENT_REFERENCE = "eventmodel";
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference databaseEvent = database.getReference(URL_EVENT_REFERENCE);
String key = "KTVAt0NM1Y5v32YxSqc";
Map<String, Object> eventValues = new HashMap<>();
eventValues.put("name", "new name");
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put(key, eventValues);
databaseEvent.updateChildren(childUpdates);
This is the JSON tree, on the eventmodel y want to update the -KTVAt0NM1Y5v32YxSqc and change the name hola to new name
{
"eventmodel" : {
"-KTVAt0NM1Y5v32YxSqc" : {
"info" : "",
"limit" : 2,
"members" : {
"Mn7gZ7rn5XRGU1HXujbbSQv05BH2" : true
},
"name" : "hola",
"pic" : "default_publish_img",
"place" : {
"address" : "Barcelona, España",
"latitude" : 41.3850639,
"longitude" : 2.1734034999999494
},
"status" : true,
"timeCurrentEnd" : "7/10/2016 21:27",
"timeCurrentStart" : "7/10/2016 20:27",
"uidLeader" : "Mn7gZ7rn5XRGU1HXujbbSQv05BH2"
}
}
}
You are putting new empty object with only name field..
try to update only the name instead of the whole object
databaseEvent.child(key).child("name").setValue("new name");
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" ]
}
}
}
}
}