Cannot update one field on firebase - Android - android

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");

Related

Sorting dates in ascending order from firebase to recyclerView

i have a problem in sorting the dates in ascending order to display in recyclerview
Here below is my database structure in firebase-realtime-database
{
firstitem : {
"name" : "first_item_name",
"date" : "29/11/2018",
"user" : "random user",
"url" : "My Url",
"tag" : "firstitem"
},
seconditem : {
"name" : "second_item_name",
"date" : "20/11/2018"
"user" : "another user",
"url" : "a url",
"tag" : "seconditem"
},
thirditem : {
"name" : "third_item_name",
"date" : "20/11/2017"
"user" : "another user",
"url" : "a url",
"tag" : "thirditem"
}
etc....
}
By using the above structure i wants to display in ascending order according to dates, What query i should do to do this, Please a give me a solution to recover from this problem ,Thanks in advance.
Query MyEventsRef = FirebaseDatabase.getInstance().getReference().child("Workers Details").child(userID)
.child("My Events").orderByChild("From_Date");
//Display events
FirebaseRecyclerOptions<WorkerMyEvents> options =
new FirebaseRecyclerOptions.Builder<WorkerMyEvents>()
.setQuery(MyEventsRef, WorkerMyEvents.class)
.build();
FirebaseRecyclerAdapter<WorkerMyEvents, WorkerMyEventViewHolder> firebaseRecyclerAdapter
= new FirebaseRecyclerAdapter<WorkerMyEvents, WorkerMyEventViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final WorkerMyEventViewHolder eventsViewHolder, int i, #NonNull final WorkerMyEvents newEvents)
{
//Id with date and time key
final String IDs = getRef(i).getKey();
final String eventIDs = IDs.substring(0,18);
final String serve = list3.get(i);
NewEventsRef.child(eventIDs).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
if (dataSnapshot.exists())
{

Unable to update value in Firebase database from Android app

With the following code, I have the "history node".
History Node
{
"History" : {
"-LJANnl9ofbXlxLGxTGg" : {
"destination" : "3 Paradise Row",
"driver" : "ReGqRl2IIUhmLIqdBqBIELHBsgE3",
"location" : "1 Union St",
"payment response" : "approved",
"rating" : 0,
"ridePrice" : 5.25,
"rider" : "l3PPyBQux7YJhGGTdexxwDBteLM2",
"riderPaid" : "true",
"status" : "accepted",
"timestamp" : 1533494377
}
}
With the following code, I am trying to update "status" value to update from "accepted" to "arrived_loc". When I run the code, I have a yellow highlight in firebase but keeps the value of status "accepted".
update status to "arrived_loc"
driverId = FirebaseAuth.getInstance().getCurrentUser().getUid();
final DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRefchild("History").orderByChild("driver").equalTo(driverId);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
DataSnapshot nodeDS = dataSnapshot.getChildren().iterator().next();
String key = nodeDS.getKey();
Log.e(TAG, "key = " + key);
String path = "/" + dataSnapshot.getKey() + "/" + key;
Log.e(TAG, "path = " + path);
HashMap<String, Object> update = new HashMap<>();
update.put("status", "arrived_loc");
rootRef.child(path).updateChildren(update);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
What am I doing wrong?
Edit #1
If I run this code:
DatabaseReference arrivedLoc = FirebaseDatabase.getInstance().getReference("History");
String historyId = arrivedLoc.push().getKey();
arrivedLoc.child(historyId).child("status").setValue("arrived at pickup");
I get an extra history node and no update:
"History" : {
"-LJAVN2iAWfRREdlBevb" : {
"destination" : "3 Union St",
"driver" : "ReGqRl2IIUhmLIqdBqBIELHBsgE3",
"location" : "123 Main Street",
"payment response" : "approved",
"rating" : 0,
"ridePrice" : 5.38,
"rider" : "l3PPyBQux7YJhGGTdexxwDBteLM2",
"riderPaid" : "true",
"status" : "accepted",
"timestamp" : 1533496391
},
"-LJAVaFd3Gzq3iIZGHeP" : {
"payment response" : "approved",
"riderPaid" : "true",
"status" : "accepted"
}
}
Edit #2 - image of database frozen
Edit #3
I can't seem to get it working for some reason so I renamed "status" to be "requestStatus" and created a new variable called rideStatus like:
status = "arrived at pickup";
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("History");
rootRef.child(requestId).child("rideStatus").setValue(status);
This seems to work for now, but when I need to change the value of rideStatus, hopefully it will work.
Try with this code without push() function:
DatabaseReference arrivedLoc = FirebaseDatabase.getInstance().getReference("History");
String historyId = arrivedLoc.getKey();
arrivedLoc.child(historyId).child("status").setValue("arrived at pickup");
(depends on what you need to achieve on your app, might be a little different)
Update #2:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("History");
addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
snapshot.getRef().child("status").setValue("arrived at pickup");
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Try with updateChildren():
driverId = FirebaseAuth.getInstance().getCurrentUser().getUid();
HashMap<String, String> newData = new HashMap<>();
newData.put("status", "arrived_loc");
final DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("History/" + driverId); // Or however the path is
rootRef.updateChildren(newData);

Firebase Data Posting

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);

orderByChild().equalTo() is always null in Firebase

I'm trying to get some data of Firebase. I'm tring to do orderby().equalTo() but I'm always getting null in my query. I've tried with two values deliveredBy (boolean) and deliveredBy (long).
Query
queryFirebase = FirebaseDatabase.getInstance().getReference().child("rooms").orderByChild("read").equalTo(false);
queryFirebase.addListenerForSingleValueEvent(new ValueEventListener() {
Send my message to Firebase
Long userId = ApplicationConfig.getCurrentUser().getId();
String toServerUnicodeEncoded = StringEscapeUtils.escapeJava(etMessage.getText().toString());
MessageFirebase message = new MessageFirebase(toServerUnicodeEncoded, new DateTime().toString("yyyy-MM-dd'T'HH:mm:ss'Z'"), userId);
DatabaseReference messageRef = mFirebaseDatabaseReference.push();
messageRef.setValue(message);
MY JSON
{
"rooms" : {
"-KtMBWKEf7-Ot8HdMtbd" : {
"-KtMC7CglZZ-Yp4_PQOU" : {
"blocked" : false,
"createDate" : "2017-09-06T14:40:17Z",
"delivered" : false,
"deliveredBy" : 317,
"difDays" : 0,
"isBlocked" : false,
"message" : "hola",
"read" : false
},
"-KtMCCdbKzP7UKFTB_qG" : {
"blocked" : false,
"createDate" : "2017-09-06T14:40:39Z",
"delivered" : false,
"deliveredBy" : 317,
"difDays" : 0,
"isBlocked" : false,
"message" : "que tal",
"read" : false
},
"commerceId" : 218,
"userId" : 317
}
}
}
read is not a direct child of rooms
You should do
queryFirebase = FirebaseDatabase.getInstance().getReference()
.child("rooms")
.child("-KtMBWKEf7-Ot8HdMtbd")
.orderByChild("read")
.equalTo(false);
queryFirebase.addListenerForSingleValueEvent(new ValueEventListener() {

Firebase Query Same Key and Count Total To Android

Here is my Firebase data:
enter image description here
I want to query same store , and count total quantity to Android ,
I have set a hashmap and listdata and listview
final Firebase myFirebaseRef = new Firebase("******");
myFirebaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot)
{
lvAll.setAdapter(null);
int size = (int) snapshot.getChildrenCount();
HashMap<String, Object> myHasMap = new HashMap<String, Object>();
listData.clear();
myHasMap.clear();
myHasMap.put("Name",coffeename[0]);
myHasMap.put("Count","Total is "+size);
listData.add(myHasMap);
listItemAdapter.notifyDataSetChanged();
lvAll.setAdapter(listItemAdapter);
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
This is JSON :
{
"5533" : {
"coffeeNo" : "美式咖啡",
"date" : 20170602,
"store" : "中正店",
"style" : "小熱"
},
"1231236" : {
"coffeeNo" : "美式咖啡",
"date" : 20170604,
"store" : "桃銘店",
"style" : "中冰"
},
"123q" : {
"coffeeNo" : "美式咖啡",
"date" : 20170603,
"store" : "中山店",
"style" : "中熱"
},
"qwe223" : {
"coffeeNo" : "美式咖啡",
"date" : 20170607,
"store" : "中山店",
"style" : "中熱"
}
}
For example : I want to query the same key , and I can get the number in store "中山店" is 2 , and in store "中正店" is 1 , and in store "桃銘店" is 1 ?
You'll need to loop over the items in the snapshot and aggregate based on the coffeeNo:
for (DataSnapshot child: snapshot.getChildren()) {
String coffeeNo = child.child("coffeeNo").getValue(String.class);
int count = 1;
if (myHashMap.containsKey(coffeeNo)) {
count = (int) myHashMap.get(coffeeNo) + 1;
}
myHashMap.put(coffeeNo, count);
}

Categories

Resources