probleme with Firebase Android pagination - android

I'm building an app which will show Posts stored on firebase. The list of Post needs to be paginated fetching most recent 10 posts at a time.
Here is the methode to load post:
private void readsposts(){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts");
reference.keepSynced(true);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
postList.clear();
for(DataSnapshot snapshot:dataSnapshot.getChildren()){
Post post = snapshot.getValue(Post.class);
for(String id:followingList){
if(post.getPublisher()!=null && post.getPublisher().equals(id)){
postList.add(post);
indication.stopShimmer();
indication.setVisibility(View.GONE);
}
}
if(post.getPublisher()!=null && post.getPublisher().equals(firebaseUser.getUid())){
postList.add(post);
//stop shimmer
indication.setVisibility(View.GONE);
indication.stopShimmer();
}
}
postAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
But above code retrieves entire list of posts instead of limited posts. How can pagination be implemented?

when you fetch data at a location in your database, you also retrieve all of its child nodes.
(because you read "Posts")
so if you Advance record your post key ,otherwise you will download data
so you can new a table of Contents to stockpile your post key

Related

variable keeps being 0

I am using firebase database and I am trying to create some sort of an index for each one of my childs -
the index itself does update but under the posts section it keeps being 0, this is the code that is responsible for updating the index
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
DatabaseReference indexReference =ref.child("postNum");
indexReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(snapshot.getValue()==null){
tempIndex = 0;
}
else {
tempIndex =(Long) snapshot.getValue();
Log.d("read", String.valueOf(tempIndex));
}
snapshot.getRef().setValue(tempIndex+1);
Log.d("temp", String.valueOf(tempIndex));
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
this is the code i use to upload new posts to firebase
Post post =new Post(etProductName.getText().toString(), date,btChooseLocation.getText().toString(),etProductPrice.getText().toString(),etProductDescription.getText().toString(),uuidImage,uid, tempIndex);
FirebaseDatabase.getInstance().getReference("Posts").child(uuidPost).setValue(post);
The problem is that your reference to postNum inside Posts table is wrong. You need to change it to ref.child("Posts").child(PostID).child("postNum");
The below solution might help you
Post post =new Post(etProductName.getText().toString(),date ,btChooseLocation.getText().toString(), etProductPrice.getText().toString(), etProductDescription.getText().toString(), uuidImage, uid, tempIndex);
//Before setting, check your POST object by printing it
//ref.child("Posts").child(yourPostID).setValue(post);
ref.child("Posts").child("a1d03799-6146-4776-9d69-73b8d9d7ae61").setValue(post);

Retrieve multiple datab by synchronization from Firebase Android

I am trying send my contacts to firebase one by one and checking if the user is present or not but due to the asynchronous behavior of firebase some information is showing twice.
I want to synchronize this method like this:
loop send one number to firebase, firebase response, save, and continue
for (int i=0 ; i< list.size();i++) {
Check_Contact(list.get(i));
}
public void Check_Contact(String number)
{
DatabaseReference myRef = database.getReference("user").child(number);
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() == null) {
}
else {
UserProfile row = dataSnapshot.getValue(UserProfile.class);
ls.add(row);
Adapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Can somebody tell me how to synchronize this method?
Firebase Structure
output coming
It is not the firebase async behaviour. You may have duplicate contents in your database. Please check ur database and update a screenshot of your database in your question.
It will be more helpful to understand your question.

Android Firebase read data issue

I'm creating an Android app for the first time, I've got a simple Realtime Firebase Database with a couple of records in it. I have the following code;
public void onStart() {
super.onStart();
// Read from the database
databaseMatches.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot matchSnapshot : dataSnapshot.getChildren()) {
matches match = matchSnapshot.getValue(matches.class);
matchesList.add(match);
}
matchList adapter = new matchList (getActivity(), matchesList);
listViewMatch.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
If I put a breakpoint on the databaseMatches.addValueEventListener(new ValueEventListener() { it shows me that the database connection has been set and is returning the correct object (In my view).
The challenge I have is the part after, the break points for public void onDataChange nor onCancelled ever get hit. I'm lost here and not sure what might be the next step as it appears to be connecting, but I am not able to retrieve records.
I'm doing this in a fragment instead of a activity. Any help is appreciated.
Detecting Connection State
it is useful for your app to know when it is online or offline. Firebase Realtime Database provides a special location at /.info/connected which is updated every time the Firebase Realtime Database client's connection state changes. Here is an example: If you are not sure.
https://firebase.google.com/docs/database/android/offline-capabilities#section-connection-state
DatabaseReference connectedRef =
FirebaseDatabase.getInstance().getReference(".info/connected");
connectedRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
boolean connected = snapshot.getValue(Boolean.class);
if (connected) {
System.out.println("connected");
} else {
System.out.println("not connected");
}
}
#Override
public void onCancelled(DatabaseError error) {
System.err.println("Listener was cancelled");
}
Firebase also loads and synchronizes data asynchronously
see Setting Singleton property value in Firebase Listener
Thanks.
There must have been some strange caching issue as the following morning when I ran the exact same code, no problem. And I've not had a problem since.

FireBase Data Retrieval is getting so much time

I am using Firebase to retrieve data and display it on android. At first it was fine but now it is taking 10 sec on addValueUpdateListner anyone know what is the problem?
final String uid1=FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference
dbref1=FirebaseDatabase.getInstance().getReference("users")
.child(uid1)
.child("signUpAs");
dbref1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
signUpOption=dataSnapshot.getValue(String.class);
Toast.makeText(getBaseContext(),signUpOption,Toast.LENGTH_LONG).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
ValueEventListener retrieves all the data at once so if your database grew up in size, it makes sense to take more time than before.

Firebase addValueEventListener excute later in loop

I am using Firebase addValueEventListener to fetch the data from firebase database, below is my code.
DatabaseReference chatMessagesDb = FirebaseDatabase.getInstance().getReference("ChatRooms");
DatabaseReference usersDb = FirebaseDatabase.getInstance().getReference("users");
chatMessagesDb.child(chatRoomId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot messages : dataSnapshot.getChildren()) {
Message message = messages.getValue(Message.class); // Message is a data Model for chatMessages.
userDb.child(message.getCreatorId()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I am applying addValueEventListener on chatMessagesDb and providing a key chatRoomId, so it will fetch all the messages from database of the chatRoom with id equals to chatRoomId. Now, for each message I want to fetch the creator of the Message, so I am adding a addValueEventListener on users database to fetch the details of the creator of a Message.
It should work like, for 1st loop of Message it should call the addValueEventListener on users db for the creator of that message, but it doesn't work like this. First, it loop through all the messages, then it starts calling addValueEventListener on users db.
How can I solve it? Please let me know if anyone have idea about this, this would be a great help.
Thanks a lot in advanced.
I think it's little late to answer, but I think other guys who are learning can be helpful. In case of message from db, use ChildValueEventListener. It returns 4 methods to implement, so any change in the db of a particular node will be listened and return that value.

Categories

Resources