I'm trying to update a specific field in a document using POJO, as written in the doc. I could use SetOptions.mergeFields(). But it's updating other fields with null instead of keeping the other fields (which excluded from mergeFields) untouched. Is it intended?
Here is my code :
UserModel userModel = new UserModel();
userModel.setStatus(0);
setTask = documentReferenceToUse.set(userModel, SetOptions.mergeFields("status"));
setTask.addOnSuccessListener(new OnSuccessListener<Void>()
{
#Override
public void onSuccess(Void aVoid)
{
if (!emitter.isDisposed())
{
emitter.onComplete();
}
}
}).addOnFailureListener(new OnFailureListener()
{
#Override
public void onFailure(#NonNull Exception e)
{
if (!emitter.isDisposed())
{
emitter.onError(e);
}
}
});
And here is my document structure :
[Solved]
Turned out the issue came from my Firebase wrapper code. So there is no actual problem on the Firebase SDL side.
Edit: After taking another closer look at your code, I found that you need to change this line of code:
setTask = documentReferenceToUse.set(model, SetOptions.mergeFields("status"));
with:
setTask = documentReferenceToUse.set(userModel, SetOptions.mergeFields("status"));
You are passing as the first argument, not the object that you have just created but another one. So, the correct object that must be used is: userModel.
You can also use another approach, by getting that entire object from the database. Having the object, you can use setters to change the value of the fileds beneath it. After you have used the setters, you can use set() method directly on the reference to add the object the database.
documentReferenceToUse.set(userModelFromDatabase);
You can also use a Map in order to make an update:
Map<String, Object> map = new HashMap<>();
map.put("status", 0);
documentReferenceToUse.update(map);
Related
If I want to add data with same key name but different values, how can I do it without replacing the existing ones? For example the database looks like this:
database
|______user1
|______sameKey: data1
|______sameKey: data2
if I use: DatabaseRef.child(user1).child("sameKey").setValue(data);, it will overwrite the sameKey with the new data, but I want it to simply be a different record of data. How to achieve that?
if you want to display a different record with the same key, just wrap it up under a push key, which is an alafanumeric random value
mDatabaseRef.child(user1).push().child("sameKey").setValue(data);
Now , if you just want to update the current data and not replace it
you will need to use a map and use updateChildren take a look at this example
Map<String,Object> mapData = new HashMap<>();
mapData.put("sameKey",data);
mDatabaseRef.child(user1).child(sameKey).updateChildren(mapData).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
// Write was successful!
// ...
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// Write failed
// ...
}
});
with this you will only replace data that is updated and not the entire node
take a look at Updating or deleting data here
https://firebase.google.com/docs/database/android/read-and-write?hl=en
I would like to update my current firebase-db to include an additional child on top of the existing ones. As of far, everytime I try implementing using the updatechildren() function, A new child outside the existing one is created.
My code:
nDatabase.child("unamrideshare")
.child(nDatabase.getKey())
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override public void onDataChange(DataSnapshot dataSnapshot) {
try {
nDatabase.child(nDatabase.getKey()).child("Called").setValue("YourDateHere");
} catch (Exception e) {
e.printStackTrace();
}
}
Anyone able to help??
To add another a new child within that db with a specific value, i.e. CurrentTime: "00:00:00" i recomand you using the following code:
nDatabase.child("unamrideshare").child("Posts").child(postId).child("CurrentTime").setValue("00:00:00");
In which postId is the unique id of the post you want to add the current time.
Hope it helps.
I am implementing firebase in my app. I have a requirement where I have to change the key value of one object. Please refer the below image as a reference to my firebase database.
For the DCu1, I need to change its key value to something else, suppose DCu4. Now for that I am creating another cloned object of DCu1 with changed key value as DCu4 and after which I will delete DCu1. The issue is with the nested parameters like DeviceList, Status, Request. How can I copy these values to the new cloned object? need your help. Thanks in advance.
When you read data at a node, all the nested stuff are downloaded.
You can use the code below:
FirebaseDatabase.getInstance().getReference().child("/path/to/DCu1").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
FirebaseDatabase.getInstance().getReference().child("path/to/DCu4").setValue(dataSnapshot.getValue());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I hope this helps
I'm trying since a while to add timestamp on my posts in Firebase, but I'm sadly unsuccessful. I have already tried many advises from stackoverflow, but none worked. Please help me on how to add a timestamp field under each post.
I would to know what's wrong with my code.
final DatabaseReference newPost = mDatabase.push();
mDatabaseUser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Long timestamp = (Long) dataSnapshot.getValue();
System.out.println(timestamp);
newPost.child("title").setValue(title_val);
newPost.child("desc").setValue(desc_val);
newPost.child("image").setValue(downloadUrl.toString());
newPost.child("uid").setValue(mCurrentUser.getUid());
newPost.child("username").setValue(dataSnapshot.child("name").getValue()).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
startActivity(new Intent(PostActivity.this, MainActivity.class));
}
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mDatabaseUser.setValue(ServerValue.TIMESTAMP);
mProgress.dismiss();
Firebase Database structure:
{
"Blog":{
"-Ke1osQRFVs0fuqx9n18":{
"desc":"again again",
"uid":"FBwMzHJGP4U10LnLOwluy4BVyJ52",
"username":"OziBoo"
}
},
"Users":{
"vi6Qd1AafidNGGV4roBhdLPZYGN2":{
"image":"firebasestorage.googleapis.com/v0/b/agrodesk-b30ff.appspot.com/...",
"name":"Ozi"
}
}
}
There are a lot of error and misuse in your code. Please understand this first:
ref.addValueEventListener(...) is used for listening to every changes made in data referenced by ref
ref.setValue(yourValue) is used to set the value of data referenced by ref object
setValue(...).addOnCompleteListener(...) is used if you want to execute something after value has been updated
If I understand it correctly, all of your sample code you write for writing value into database, right? But you, not knowingly, used addValueEventListener() instead.
So your code to write the value into new child inside "Blog" should be like this:
// Here I use HashMap to make it more simple
// You can (and better to) use your custom object as value container
HashMap<String, Object> value = new HashMap<>();
value.put("title", "your-title");
value.put("desc", "your-desc");
value.put("timestamp", ServerValue.TIMESTAMP);
// ... etc
// the following code will create a reference object pointing at "Blog"
DatabaseReference ref = FirebaseDatabase.getInstance().getRreference("Blog");
// the following code will make a new child inside data referenced by ref (in this case, "Blog")
DatabaseReference newBlog = ref.push();
// the following code is the code that actually update the data of referenced point
newBlog.setValue(value)
// addOnCompleteListener is optional
.addOnCompleteListener(new ... {
// code placed here will be executed when your data is updated
...
});
Hope this helps.
Note:
There I just show you what you want to achieve for this case and this case only. Please read more documentation, guide, and tutorial about Firebase Database. It might take long, but once you understand it, it's actually quite simple.
I have the following data structure on firebase for the user MF0qeRA4p7djfjgXxqwFOck3m6p02. I want to get the value of item3 to populate a single field into the User interface on an Android App. I have been looking through samples on Stackoverflow, but all I have found are outdated and do not work with the current version of firebase. I'm new to firebase completely and this is my first app on android. I've got the oncreate user method to populate the users email address and add the 4 item fields, but retrieving the data I'm completely lost and I am not sure where to even begin.
-Users
---MF0qeRA4p7djfjgXxqwFOck3m6p02
------item1:"1"
------item2:"2"
------item3:"3"
------item4:"4"
According to what I can identify is, you are facing problem retrieving data from this reference. Here is the code:
final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Users");
databaseReference.child("MF0qeRA4p7djfjgXxqwFOck3m6p02").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String, Object> map=(Map<String, Object>)dataSnapshot.getValue();
String item3=(String)map.get("item3");
display(item3);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Hope this helps.
You can create a custom model and inside you can insert elements. Something like this:
public class Item {
private List<Object> ojects;
}
There you can save instance of Item on database. In this case you have more controll. Other case is to use push() method, that will generate a new encoded key, something like this:
mDatabase.child("items").push().put(new Object());