I am having an app with a Swipe-To-Refresh layout.
When you scroll up in a Swipe-To-Refresh layout, data refreshes from the internet. (for those who don't know)
My data source is Firebase.
In my app if the user is not connected, then it shows a network error message, then after the internet is turned on it doesn't get the data.
How do you I get data again from my database.
Here is the code:
protected void onCreate(Bundle savedInstanceState) {
...
mFirebaseDatabase = FirebaseDatabase.getInstance();
// my database
mNewsDatabaseReference = LoginActivity.mFirebaseDatabase.getReference()
.child("data").child("news");
// my database reference
// my ChildEventListener
mNewsChildEventListener = new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
// my data
News news = dataSnapshot.getValue(News.class);
// add the news to the top of my ArrayAdapter
myAdapter.insert(news, 0);
}
@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) {}
};
// my OnRefreshListener
mySwipeRefreshLayout.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
// what Should I do in here to request the data again?!
// I know that I should empty my adapter first then request the data
myAdapter.clear();
}
}
);
}
When using firebase realtime-database, there is no need to do the request again. Once the data changes, it will automatically fetch the data for you and one of your listeners is going to be called.
Your onChildChanged() event will be fired any time a news
child node is modified, including any modifications to descendants of the child node.
To enable Offline Capabilities don't forget to use setPersistenceEnabled(true)
Check out the documentation for more info
The answer above is most helpful, but for the question how to request data again?!
You simply need to attach the listeners one more time.
But remember to detach the old listeners first so that data doesn't appear twice in the adapter.
Here is the code:
mNewsSwipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
myAdapter.clear();
mNewsDatabaseReference.removeEventListener(mNewsChildEventListener);
mNewsDatabaseReference.addChildEventListener(mNewsChildEventListener);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With