How do I arrange items by newest

Viewed 33

I have an application to post articles The data is saved in Firebase I want articles to be sorted by Newest how I can do that I have an application to post articles The data is saved in Firebase I want articles to be sorted by Newest how I can do that

 private void postDataLoad() {
        postDatabaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                postList.clear();
                for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
                    PostModel model = dataSnapshot.getValue(PostModel.class);
                    postList.add(model);


                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
            }
        });
    }

    private void profileDataListLoad() {
        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                profileList.clear();
                for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
                    ProfileModel profileModel = dataSnapshot.getValue(ProfileModel.class);
                    if (!currentId.equals(profileModel.getId())) {
                        profileList.add(profileModel);
                    }
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });
    }

1 Answers

Use below code It will work for you -

While adding a post using one more param "timestamp" -

HashMap<String, Object> map = new HashMap<>();
                map.put("post", strPost);
                map.put("name", model.getName());
                map.put("id", model.getId());
                map.put("imageUrl", model.getImageUrl());
                map.put("timestamp", ServerValue.TIMESTAMP);

While Fetching data from Realtime DB use below Query -

Query postQuery = postDatabaseReference.orderByChild("timestamp");
Related