How can I add to a list in a Firebase Realtime Database transaction using MutableData?
In a normal non-transaction type update, I can simply use
DatabaseReference refDatabase = ...
refDatabase.push().setValue(value);
But with MutableData, no such push() method exists. How to add to a list and get a unique key?
I'm looking for something like
public Transaction.Result doTransaction(MutableData mutableData) {
mutableData.push().setValue(value);
...
but this does not exist.
I think I understand the point of your question and comment: It would be nice to know if the absence of push() was an oversight by the API designers, or it was intentionally omitted to prevent users from doing something that was unsafe or otherwise "bad".
There is a workaround, right? You know the reference the transaction is run on. The mutable data is the value of that reference location. Can't you just make the reference variable a package field, or a final class variable, and use it in the callback to call push()? It's ugly, but I think should work.
I'll also take a guess that push() was omitted from MutableData for a reason. The documentation for doTransaction() states:
This method will be called, possibly multiple times, with the current
data at this location. It is responsible for inspecting that data and
returning a Transaction.Result specifying either the desired new data
at the location or that the transaction should be aborted.
Since this method may be called repeatedly for the same transaction,
be extremely careful of any side effects that may be triggered by this
method.
Maybe generating keys and adding elements to a list is not something you want to be doing, since it may occur multiple times.
Related
I have two activities. First activity shows list of notes. Notes themselves are lists.
I use Android Architecture Components: ViewModel, LiveData; with Repository, Room, Dao, etc.
So, I make a method getAllNotes() in Dao, Repository and ViewModel like in google sample apps. In onCreate method of first activity I call observe and set adapter's content of a RecyclerView. And it works fine - it shows the list with Note titles.
Like that:
override fun onCreate(savedInstanceState: Bundle?) {
//some code
viewModel = obtainViewModel()
viewModel.getAllNotes().observe(this, Observer<List<Notes>> { notes ->
recView.setNote(notes)
}
}
Then I have a button that starts new Activity to create new Note. That note contains list of Lines which for now contains only string and foreign key.
data class Line {
var id: Long? = null
var note_id: Long? = null
var payload: String? = null
}
Note and Line are one-to-many relation and they are connected by id of Note and foreign key note_id in Line.
(I don't write here all of the code, it works, trust me)
The problem is, that to insert Lines in database I firstly need to insert the parent Note and I do that. And it works almost OK too. But the liveData of the getAllNotes() from the first Activity gets notified by this insertion. And if the user, as a result, decides to delete all the lines and go back to the first activity even if I delete temporary Note entity from the database the list on the first Activity shows it for a moment because it gets deleted in a background with a small delay.
What I see as a solution:
1) Unsubscribe observers from livedata. I tried to do it in onStop method, but it gets called after the onCreate method of the second activity where the entity is being created, so the livedata already gets notified and observers are removed after temporary Note passed into the list.
2) Not use Room/SQLite as cache. Since this Note and Lines are not guaranteed to stay then and shouldn't be shown or inserted into a table. So, I can keep it all in properties of viewModel (i.e. in memory). But I see a lot of overhead work to save these entities through screen rotation, minimizing the app and all that stuff with saving state and restoring it.
3) Create two additional entities like CachedNote and CachedLine and corresponding tables, to work with it until I decide to persist the work, insert it into original tables and show it.
4) Add property to the Note entity like "visible" and add this parameter to Query, to make entity note shown, until I decide to persist the work. But there could be a lot of "updateNoteWithLines" every where.
What should I do? I didn't google anything useful.
I know it's like "What's the best way question", forgive me.
You can try to call the observe in onResume and then call removeObserver in onPause, that way the Activity will not be updated, please look at the example here.
I want to get the data stored in the DB without being restricted to access it only when there is a data change.
I've seen this post from 2016:
How to access Firebase data without using addValueEventListener
Which suggested to use addValueEventListener.
I've also seen this post:
Accessing data in Firebase databse
Without good answer.
ValueEventListener will trigger the onDataChange only when the database will have a change.
How else can I access the database without something being changed in the database?
For now I will write simple harmless change in order to access the data, but i'm wondering if it's the only way to do it.
Thanks
Of course this is absolutely not true. You can retrieve data whenever you like to.
Firstly I would like to advice you to read this documentation reference.
Secondly I provide you with what you really asked for.
If you read the documentation you will notice that it states the following:
The onDataChange() method in this class is triggered once when the listener is attached and again every time the data changes, including the children.
That means that with this code:
databaseReference.removeEventListener(eventListener);
With that method you would be able to detatch any listener so it only listens once or detatch it whenever you want to.
There is a method for only retrieving data once though.
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d(TAG, "Data retrieved.");
}
...
}
This method will exactly call onDataChange once or respectively onCancelled.
Currently, the Google's version of ServerValue.TIMESTAMP returns {".sv":"timestamp"} which is used as a directive for Firebase to fill that field with the server timestamp once you save the data to the Firebase server.
When you create your data on the client side however, you don't have the actual timestamp to play with yet (ie. use as the creation date). You only will have an access to the timestamp after the initial save and consequent retrieval, which - I imagine - is sometimes too late and not very elegant.
Before Google:
Update: Ignore this section as it is incorrect - I misunderstood the examples. ServerValue.TIMESTAMP always returned the {".sv":"timestamp"}.
As far as I understand in pre-google Firebase there seemed to be a server-generated timestamp available that allowed you to acquire the actual timestamp:
import com.firebase.client.ServerValue;
ServerValue.TIMESTAMP // eg. 1466094046
(ref 1, ref 2)
Questions:
Is such save/retrieval the only way to get the server-generated creation date on my model instances?
If yes can you propose a method of implementing such pattern?
Am I understanding correctly ServerValue.TIMESTAMP has changed with Google's acquisition of Firebase? Update: No, #FrankvanPuffelen replied that nothing's changed during acquisition.
Note:
I'm not considering using new Date() on client side as I've been reading it's not safe, though please share your thoughts if you think different.
When you use the ServerValue.TIMESTAMP constant in a write operation, you're saying that the Firebase Database server should determine the correct timestamp when it executes the write operation.
Let's say we run this code:
ref.addValueEventListener(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
System.out.println(dataSnapshot.getValue());
}
public void onCancelled(DatabaseError databaseError) { }
});
ref.setValue(ServerValue.TIMESTAMP);
This will execute as follows:
you attach a listener
you write a value with ServerValue.TIMESTAMP
the Firebase client immediate fires a value event with an approximation of the timestamp it will write on the server
your code prints that value
the write operation gets sent to the Firebase servers
the Firebase servers determine the actual timestamp and write the value to the database (assuming no security rules fail)
the Firebase server send the actual timestamp back to the client
the Firebase client raises a value event for the actual value
your code prints that value
If you're using ChildEventListener instead of a ValueEventListener, then the client will call onChildAdded in step 3 and onChildChanged in step 8.
Nothing changed in the way we generate the ServerValue.TIMESTAMP since Firebase joined Google. Code that worked before, will continue to work. That also means that the first answer you linked is a valid way to handle it.
I'm doing it a bit differently.
Solution 1: push() method in POJO
As I don't want to clutter my POJOs with strange getters or properties, I'm just defining a push() method inside my POJOs which looks like this:
/**
* Pushes a new instance to the DB.
*
* #param parentNode `DatabaseReference` to the parent node this object shall be attached to
*/
fun push(parentNode: DatabaseReference) {
parentNode
.push()
.apply {
setValue(this#Pojo)
child(Pojo.CREATED_AT_KEY).setValue(ServerValue.TIMESTAMP)
}
}
Then I can simply create an instance of the POJO and call push() on it which properly populates the creation time property.
This definitely makes the POJO a little less plain and involves logic a POJO shouldn't know about. However using #Exclude annotations and/or casts as outlined in some of the responses here also requires knowledge of the storing mechanism.
Solution 2: Helper or DatabaseReference extension (Kotlin)
To overcome this you can of course also just create a pushTask(task: Task) method in a helper or - if using Kotlin - an extension method to e.g. DatabaseReference which could look like this:
fun DatabaseReference.push(pojo: Pojo) {
push()
.apply {
setValue(pojo)
child(Pojo.CREATED_AT_KEY).setValue(ServerValue.TIMESTAMP)
}
}
Looking at it now I come to think that I actually like the second approach more (if I have Kotlin at my disposal - I don't like helpers). But this is probably just a matter of taste. ;)
Currently, the Google's version of ServerValue.TIMESTAMP returns {".sv":"timestamp"} which is used as a directive for Firebase to fill that field with the server timestamp once you save the data to the Firebase server.
When you create your data on the client side however, you don't have the actual timestamp to play with yet (ie. use as the creation date). You only will have an access to the timestamp after the initial save and consequent retrieval, which - I imagine - is sometimes too late and not very elegant.
Before Google:
Update: Ignore this section as it is incorrect - I misunderstood the examples. ServerValue.TIMESTAMP always returned the {".sv":"timestamp"}.
As far as I understand in pre-google Firebase there seemed to be a server-generated timestamp available that allowed you to acquire the actual timestamp:
import com.firebase.client.ServerValue;
ServerValue.TIMESTAMP // eg. 1466094046
(ref 1, ref 2)
Questions:
Is such save/retrieval the only way to get the server-generated creation date on my model instances?
If yes can you propose a method of implementing such pattern?
Am I understanding correctly ServerValue.TIMESTAMP has changed with Google's acquisition of Firebase? Update: No, #FrankvanPuffelen replied that nothing's changed during acquisition.
Note:
I'm not considering using new Date() on client side as I've been reading it's not safe, though please share your thoughts if you think different.
When you use the ServerValue.TIMESTAMP constant in a write operation, you're saying that the Firebase Database server should determine the correct timestamp when it executes the write operation.
Let's say we run this code:
ref.addValueEventListener(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
System.out.println(dataSnapshot.getValue());
}
public void onCancelled(DatabaseError databaseError) { }
});
ref.setValue(ServerValue.TIMESTAMP);
This will execute as follows:
you attach a listener
you write a value with ServerValue.TIMESTAMP
the Firebase client immediate fires a value event with an approximation of the timestamp it will write on the server
your code prints that value
the write operation gets sent to the Firebase servers
the Firebase servers determine the actual timestamp and write the value to the database (assuming no security rules fail)
the Firebase server send the actual timestamp back to the client
the Firebase client raises a value event for the actual value
your code prints that value
If you're using ChildEventListener instead of a ValueEventListener, then the client will call onChildAdded in step 3 and onChildChanged in step 8.
Nothing changed in the way we generate the ServerValue.TIMESTAMP since Firebase joined Google. Code that worked before, will continue to work. That also means that the first answer you linked is a valid way to handle it.
I'm doing it a bit differently.
Solution 1: push() method in POJO
As I don't want to clutter my POJOs with strange getters or properties, I'm just defining a push() method inside my POJOs which looks like this:
/**
* Pushes a new instance to the DB.
*
* #param parentNode `DatabaseReference` to the parent node this object shall be attached to
*/
fun push(parentNode: DatabaseReference) {
parentNode
.push()
.apply {
setValue(this#Pojo)
child(Pojo.CREATED_AT_KEY).setValue(ServerValue.TIMESTAMP)
}
}
Then I can simply create an instance of the POJO and call push() on it which properly populates the creation time property.
This definitely makes the POJO a little less plain and involves logic a POJO shouldn't know about. However using #Exclude annotations and/or casts as outlined in some of the responses here also requires knowledge of the storing mechanism.
Solution 2: Helper or DatabaseReference extension (Kotlin)
To overcome this you can of course also just create a pushTask(task: Task) method in a helper or - if using Kotlin - an extension method to e.g. DatabaseReference which could look like this:
fun DatabaseReference.push(pojo: Pojo) {
push()
.apply {
setValue(pojo)
child(Pojo.CREATED_AT_KEY).setValue(ServerValue.TIMESTAMP)
}
}
Looking at it now I come to think that I actually like the second approach more (if I have Kotlin at my disposal - I don't like helpers). But this is probably just a matter of taste. ;)
Currently, the Google's version of ServerValue.TIMESTAMP returns {".sv":"timestamp"} which is used as a directive for Firebase to fill that field with the server timestamp once you save the data to the Firebase server.
When you create your data on the client side however, you don't have the actual timestamp to play with yet (ie. use as the creation date). You only will have an access to the timestamp after the initial save and consequent retrieval, which - I imagine - is sometimes too late and not very elegant.
Before Google:
Update: Ignore this section as it is incorrect - I misunderstood the examples. ServerValue.TIMESTAMP always returned the {".sv":"timestamp"}.
As far as I understand in pre-google Firebase there seemed to be a server-generated timestamp available that allowed you to acquire the actual timestamp:
import com.firebase.client.ServerValue;
ServerValue.TIMESTAMP // eg. 1466094046
(ref 1, ref 2)
Questions:
Is such save/retrieval the only way to get the server-generated creation date on my model instances?
If yes can you propose a method of implementing such pattern?
Am I understanding correctly ServerValue.TIMESTAMP has changed with Google's acquisition of Firebase? Update: No, #FrankvanPuffelen replied that nothing's changed during acquisition.
Note:
I'm not considering using new Date() on client side as I've been reading it's not safe, though please share your thoughts if you think different.
When you use the ServerValue.TIMESTAMP constant in a write operation, you're saying that the Firebase Database server should determine the correct timestamp when it executes the write operation.
Let's say we run this code:
ref.addValueEventListener(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
System.out.println(dataSnapshot.getValue());
}
public void onCancelled(DatabaseError databaseError) { }
});
ref.setValue(ServerValue.TIMESTAMP);
This will execute as follows:
you attach a listener
you write a value with ServerValue.TIMESTAMP
the Firebase client immediate fires a value event with an approximation of the timestamp it will write on the server
your code prints that value
the write operation gets sent to the Firebase servers
the Firebase servers determine the actual timestamp and write the value to the database (assuming no security rules fail)
the Firebase server send the actual timestamp back to the client
the Firebase client raises a value event for the actual value
your code prints that value
If you're using ChildEventListener instead of a ValueEventListener, then the client will call onChildAdded in step 3 and onChildChanged in step 8.
Nothing changed in the way we generate the ServerValue.TIMESTAMP since Firebase joined Google. Code that worked before, will continue to work. That also means that the first answer you linked is a valid way to handle it.
I'm doing it a bit differently.
Solution 1: push() method in POJO
As I don't want to clutter my POJOs with strange getters or properties, I'm just defining a push() method inside my POJOs which looks like this:
/**
* Pushes a new instance to the DB.
*
* #param parentNode `DatabaseReference` to the parent node this object shall be attached to
*/
fun push(parentNode: DatabaseReference) {
parentNode
.push()
.apply {
setValue(this#Pojo)
child(Pojo.CREATED_AT_KEY).setValue(ServerValue.TIMESTAMP)
}
}
Then I can simply create an instance of the POJO and call push() on it which properly populates the creation time property.
This definitely makes the POJO a little less plain and involves logic a POJO shouldn't know about. However using #Exclude annotations and/or casts as outlined in some of the responses here also requires knowledge of the storing mechanism.
Solution 2: Helper or DatabaseReference extension (Kotlin)
To overcome this you can of course also just create a pushTask(task: Task) method in a helper or - if using Kotlin - an extension method to e.g. DatabaseReference which could look like this:
fun DatabaseReference.push(pojo: Pojo) {
push()
.apply {
setValue(pojo)
child(Pojo.CREATED_AT_KEY).setValue(ServerValue.TIMESTAMP)
}
}
Looking at it now I come to think that I actually like the second approach more (if I have Kotlin at my disposal - I don't like helpers). But this is probably just a matter of taste. ;)