How to retrieve a List from Firebase avoid asynchronous - android

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

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 fetch only updated object from Relatime Firebase Database?

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.

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

Unable to retrieve data from Firebase Realtime Database

I'm trying to display the "loc" of a part if its part number I given.
Here is what the data structure looks like:
{
"parts":{
"14521845": { "name":"TOOL EC160B/EC180B/EC210B/EC240", "loc":"EXC1", "sloc":"B3EGU01C03"},
"12829050": { "name":"SWITCH; IGNITION SWITCH", "loc":"PS01", "sloc":"85-06-013"},
"12829050": { "name":"SWITCH; IGNITION SWITCH", "loc":"COM1", "sloc":"B3RGK03D06"},
"20044893": { "name":"PARTS CATALOG_ENG_SPA_FRE_GER_KOR_EC210D", "loc":"EXC1", "sloc":"B3EGT01B02"}
}
}
Activity Code:
FirebaseDatabase firebaseDatabase=FirebaseDatabase.getInstance();
DatabaseReference databaseReference =firebaseDatabase.getReference("parts/"+curP);
databaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Products data=dataSnapshot.getValue(Products.class);
Log.i("",String.valueOf(data.getLoc()));
}
getLoc is the getter function for the Product class, and it returns the corresponding "loc" for the given curP. curP denoted the child values in parts.
The logic seems right to me, but I am not getting an output. Where am I going wrong here?
try this
getReference("parts").child(curP).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Products data = dataSnapshot.getValue(Products.class);
Log.i("", String.valueOf(data.getLoc()));
}
});
The problem is that what you are getting in onChildAdded() is not a whole Product object as you expect it to be.
In your database reference you are targeting a specific Product ("parts/"+curP) but using a ChildEventListener. The children of a specific product node are name, loc and sloc, so the onChildAdded() will trigger several times, giving you each of these properties as a dataSnapshot separately.
The two patterns you might use to get whole Product objects are either:
add a ChildEventListener directly to the "parts" node and you will get each of the Products as a child of that node, or;
if you are adding a listener directly to the node of a particular product, use a ValueEventListener, to get the whole of that nodes entry as one dataSnapshot.
You can try to use ValueEventListener. If you want read data once so use the addListenerForSingleValueEvent method, something like this:
private void getFirebaseLocValue(int curP) {
FirebaseDatabase firebase = FirebaseDatabase.getInstance();
DatabaseReference mDatabase = firebase.getReference("parts");
mDatabase.child(Integer.toString(curP))
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChildren()) {
Products data = dataSnapshot.getValue(Products.class);
Log.e("TAG", data.getLoc());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Or you can use addValueEventListener and will get data with any changes. I really don't think that ChildEventListener is a good idea to retrieve data from Firebase.

Categories

Resources