Search code examples
javaandroidfirebase-realtime-databaseandroid-listviewfirebaseui

How to display a listview by comparing values in android


I have an app with a listview. Currently it shows all data that I input to the database. I want to display data from firebase database by comparing current time and the time that I input to the database.

here is the code

 lv = findViewById(R.id.listView);
        Query query = FirebaseDatabase.getInstance().getReference().child("Details");
        FirebaseListOptions<Member> options = new FirebaseListOptions.Builder<Member>()
                .setLayout(R.layout.list_view_item)
                .setQuery(query,Member.class)
                .build();
        adapter = new FirebaseListAdapter(options) {
            @Override
            protected void populateView(@NonNull View v, @NonNull Object model, int position) {
                check();

                TextView loc = v.findViewById(R.id.locs);
                TextView des = v.findViewById(R.id.dests);
                TextView bus = v.findViewById(R.id.busn);
                TextView tim = v.findViewById(R.id.time);

                Member db = (Member) model;
                loc.setText(db.getLocation().toString());
                des.setText(db.getDestination().toString());
                bus.setText(db.getBusname().toString());
                tim.setText(db.getTime().toString());
            }
        };
        lv.setAdapter(adapter);

}

 @Override
    protected void onStart() {
        super.onStart();
        adapter.startListening();
    }


@Override
    protected void onStop() {
        super.onStop();
        adapter.stopListening();
}

Any error please guide me, I am new in Android. Thanks in Advance :)


Solution

  • You're looking for Firebase Database queries, which allow you to filter data on the Firebase servers. Say that you have a field that holds a timestamp for each node under details (the number of milliseconds since January 1, 1970). You can get every child node from between one and two weeks ago with:

    Query query = FirebaseDatabase.getInstance().getReference().child("Details");
    
    long oneWeekInMillis = 7 * 24 * 60 * 60 * 1000;
    long oneWeekAgo = System.currentTimestampMillis() - oneWeekInMillis;
    long twoWeeksAgo = oneWeekAgo - oneWeekInMillis;
    
    query = query.orderByChild(timestamp).startAt(twoWeeksAgo).endAt(oneWeekAgo);
    

    And you can just pass this query into the adapter, like you're already doing.