How to fetch only updated object from Relatime Firebase Database? - android

I am new to Firebase Real-time Database and don't have an idea that how to fetch only the recent updated object from the table.
I have tried using "ChildEventListener" but when I initialize the Listener for the first time it fetches the last row from the database.
It should not be fetched if it was not updated.
I want object only when it is updated or newly added.
I have done this,
databaseReference.child("last_chat").orderByChild("s_id").equalTo(preference.getUserData().getId()).limitToLast(1).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Log.e("dataSnapShot", dataSnapshot.toString() + " " + s);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Log.e("dataSnapShotChagned", dataSnapshot.toString() + " " + s);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Log.e("dataSnapShotRemoved", dataSnapshot.toString());
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e("onCalcnelle", databaseError.toString());
}
});
Thank you in advance.

I have solved the issue.
I just need to put my code inside the OnChildChanged instead of putting my code in OnChildAdded.
Log dataSnapShot shown when first running the application, whereas as soon as I change or update object dataSnapShotChagned is shown.
Thus it worked for me, OnChildAdded method is called every time while initializing the listener where OnChildChanged method is called only when there is a change in a particular object.
Thanks a lot all for the help.

public ValueEventListener addValueEventListener (ValueEventListener listener)
Also: Google Play services
Add a listener for changes in the data at this location. Each time time the data changes, your listener will be called with an immutable snapshot of the data.
Firebase Doc
Hope this helps.

Related

how to update recycleview when data is inserted in firebase?

How can i implement a listener on firebase to keep check if data has changed in firebase? for example, a user insert a data in firebase, a second user is checking a listview of that data, i want to refresh that listview automatically.
You need to listen to Firebase Database changes, and once data added to the database, you will be notified on client side and you will receive the data that is added to firebase database because it's realtime database.
mFirebaseDatabase.child("yourNode").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
// here you need to handle the value added.
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
There are two ways.
Way 1: If possible, create a callback and after user insert a new item, you callback will fire.
Way 2: Every N second (2-5), you could make a request to server to ask him if new data avaliable.
Also if you are building a list with recyclerView, for efficient updating list, use DiffUtil.
Which case is better, you decide. I don't work with firebase list.

How to retrieve a List from Firebase avoid asynchronous

I know that when we retrieve data from Firebase ,it will be asynchronous, so ussally i will put all the code inside addChildEventListener, like example i want to sort userList below. But i am confused, if the List is really big, like million Users, so it means the method sortUser(user) will be called million times ? Can anyone explain this to me, I'm new to firebase
myRef.child("User").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
User user= dataSnapshot.getValue(User.class);
userList.add(user);
sortUser(userList);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
You currently use a ChildEventListener, which means your onChildAdded gets called for each child node immediately and then later whenever a new child is added. This indeed can be a lot of invocations.
If you use a ValueEventListener, its onDataChange will only be called once for the initial data (no matter how many child nodes there are), and then once for each change.
By adding a ValueEventListener to your current set up, you can keep things simple: add the child nodes to the lit like you're already doing, but only sort in onDataChange.
myRef.child("User").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
sortUser(userList);
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
};
Firebase will only synchronize the data for the User node once, even when you have two listeners on it.
You should probably retrieve the data sorted server side by using order-by methods and then listen to that one.
var userRef = firebase.database().ref('posts').orderByChild('Users');
If I guess correctly, you would not need separate sorting client side.
You can also filter data. Do refer the docs

Firebase: Read Data once activity started

is there any ways to read data from Firebase once the Activity is loaded. At this moment I am using the regular valueEventListener, but in order for it to work, there has to be some sort of a change in the database
mDatabaseReference.child("Users").child(mUser.getUid()).
child("Posts").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
arrayOfQuestionForms.clear();
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
QuestionForm tempQuestionForm = postSnapshot.getValue(QuestionForm.class);
arrayOfQuestionForms.add(tempQuestionForm);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
What I am looking for is some way to read data from Firebase without using listeners. I have looked at other similar posts but I don't think there is a clear answer for this yet.
There is no way for reading data from a Firebase database without using listeners. Everything is about listeners when it comes to Firebase. It's true that when setting a value, we just need to use a method named setValue() directly on the reference. Unfortunately, there is no method within Firebase, let' say getValue(), which acts in the same way as setValue().
To solve this, i recommend you using addListenerForSingleValueEvent.
Add a listener for a single change in the data at this location. This listener will be triggered once with the value of the data at the location.
in order for it to work, there has to be some sort of a change in the database
This is not true and a common source of confusion for developers.
With your current code, Firebase will immediately start reading the data from the server. Once it gets that data, it invokes your onDataChange().
From the documentation:
This method is triggered once when the listener is attached and again every time the data, including children, changes.
for such purpose I used different kind of listener - ChildEventListener. It has different #Override methods. The method onChildAdded returns every child-nodes of the node when called first time (i.e. on activity start).
Put attention - maybe you will need to slightly change the reference to DB (trim back one hierarchy level), to point to the parent node. If you expanded snapshot of your DB structure, I can look.
Here is updated code (sorry is made any typo - I couldn't test it as have no your DB :)
mDatabaseReference.child("Users").child(mUser.getUid()).child("Posts").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
arrayOfQuestionForms.clear();
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
QuestionForm tempQuestionForm = postSnapshot.getValue(QuestionForm.class);
arrayOfQuestionForms.add(tempQuestionForm);
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

firebase android multiple event listener callBacks on static variable

discussionReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Discussion discussion = dataSnapshot.getValue(Discussion.class);
discussionAdapter.add(discussion);
//cancel spinner
t[0]++;
if(t[0]>=2)setNormalScreen();
ObjectsKeysManager.discussionIds.add(dataSnapshot.getKey());/*this is my static variable*/
discussionAdapter.notifyItemInserted(ObjectsKeysManager.discussionIds.size()-1);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Discussion newDiscussion = dataSnapshot.getValue(Discussion.class);
String discussionKey = dataSnapshot.getKey();
int discussionIndex = ObjectsKeysManager.discussionIds.indexOf(discussionKey);
if(discussionIndex>-1)
{
discussionAdapter.update(newDiscussion, discussionIndex);
discussionAdapter.notifyItemChanged(discussionIndex);
}
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot)
{
Discussion removedDiscussion = dataSnapshot.getValue(Discussion.class);
int index = ObjectsKeysManager.discussionIds.indexOf(dataSnapshot.getKey());
ObjectsKeysManager.discussionIds.remove(index);/*here its changed*/
discussionAdapter.removeElement(removedDiscussion);
discussionAdapter.notifyDataSetChanged();
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
what if the user1 adds child, user2 removes child, user3 updates another child at the exact same time. Its obvious that ObjectsKeysManager.discussionIds is in all . How to lock the variable ObjectsKeysManager.discussionIds ? or how to professionaly implement this ?
additionally
do onChildAdded(), onChildChanged(), onChildRemoved() wait for each other?
To solve this problem, i recomand you using transaction operation. This is the best way in which you can achieve this, when we are talking about concurrent modifications.
I recomand you also using ValueEventListener that has only one method named onDataChange() which reads and listens for changes to the entire contents of a specific path.
Hope it helps.
as #Alex Mamo suggested I have been studying Transaction class and transaction only helped for a single node, but in my case the big problem was to make onChildEventListener() thread safe (I dont know if it is by default but didn't take the risk) ,the solution I came up is making a method public synchronized void onChildModified(DataSnaphot dataSnaphot, String type) and redirected onChildChanged() and onChildRemoved() to it by passing the snapshot as parameter, this made any event that happened go directly to the synchronized method and saved the day, about the onChildAdded() its not necessary to make is thread safe reason being in order to change and remove the child it must be added so no need to put it inside onChildModified() (even if you did probably gonna have some errors because of the iteration of the snapShot).

FireBase onChildAdded() triggers onChildRemoved()

I am trying to understand how the two are related. From the docs:
onChildAdded event is triggered once for each existing child and then again every time a new child is added to the specified path. The listener is passed a snapshot containing the new child's data.
And that:
The onChildRemoved event is triggered when an immediate child is removed. It is typically used in conjunction with onChildAdded and onChildChanged events. The snapshot passed to the event callback contains the data for the removed child.
So techincally i was expecting that the two events are triggered separately based on their roles: that is, onChildAdded will be triggered when i add new data while onChildRemoved is when i delete a child from the nodes.
However, when i add data this is what i log:
14:47:39.649 31305-31305/com.myapp D/addData_: onChildRemoved called
14:47:39.649 31305-31305/com.myapp D/addData_: onChildAdded called
onChildRemoved is called first before onChildAdded!! What's worse is that the data disappears from my listview. Someone help me understand what it is i'm doing wrong.
This is my data structure:
And my firebase ref:
ref = FirebaseDatabase.getInstance().getReference().child("sales/" + getId() + "/" + getDateTime());
//limit to the last data
final Query lastSale = ref.limitToLast(1);
//add on child event listener
lastSale.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
//get the data from firebase and add it to our model
MyModel model = dataSnapshot.getValue(MyModel.class);
String firebase_key = dataSnapshot.getKey();
Log.d("addData_", "onChildAdded called");
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Log.d("addData_", "onChildChanged called");
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Log.d("addData_", "onChildRemoved called");
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
Log.d("addData_", "onChildMoved called");
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I commented out his line and it worked!
//limit to the last data
final Query lastSale = ref.limitToLast(1);

Categories

Resources