Home > database >  Filtering by month using spinner in recyclerview in android studio firebase
Filtering by month using spinner in recyclerview in android studio firebase

Time:10-30

I'm using Android Studio and the Realtime Database as my database, January will be "0" in months, and October will be "9". I tried this and still unknown what to do in this if condition, I just need to put in the if statement to filter the information I get by month. This is the app I'm trying to sort it by month, tried sorting to February, BUT appointments from month 9 still show up. I want to Filter the appointments by months

APP is here

database is here

public class adminAppoinment extends AppCompatActivity {

    ImageView drawerButton;
    RecyclerView recyclerView;
    List<Bookings>bookingsList;
    List<ModelUser>modelUsers;
    AppointmentAdapter appointmentAdapter;
    Spinner months;
    String month;

    private ActivityAdminAppoinmentBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityAdminAppoinmentBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        NavigationView navigationView = (binding.navView);
        navigationView.setCheckedItem(R.id.nav_adminAppointment);

        DrawerLayout drawerLayout = (binding.drawerLayout);
        drawerButton = (binding.hamburger);

        drawerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                drawerLayout.openDrawer(GravityCompat.START);
            }
        });

        recyclerView = binding.recyclerView;
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getApplication()));
        bookingsList = new ArrayList<>();
        modelUsers = new ArrayList<>();

        months = binding.spinner3;

        ArrayAdapter<CharSequence>adapterMonth = ArrayAdapter.createFromResource(this,R.array.months, androidx.appcompat.R.layout.support_simple_spinner_dropdown_item);
        adapterMonth.setDropDownViewResource(androidx.appcompat.R.layout.support_simple_spinner_dropdown_item);
        months.setAdapter(adapterMonth);
        months.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                month = parent.getItemAtPosition(position).toString();


                DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Bookings").child("bookingDetails");
                Query query;
                //if january then 1, then filter by month 1 from database

                if (month.equals(1)){
                    query = ref.orderByChild("bookingDetails").equalTo("February");
                }
                else if (month.equals(9)) {
                    query = ref.orderByChild("bookingDetails").equalTo("October");
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                getAllBooks();

            }
        });


        getAllBooks();

        navigationView.setCheckedItem(R.id.nav_adminAppointment);
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()){
                    case R.id.nav_home:
                        startActivity(new Intent(getApplication(), govethome2.class));
                        drawerLayout.closeDrawer(GravityCompat.START);
                        finishAfterTransition();
                        break;
                    case R.id.nav_adminUsers:
                        startActivity(new Intent(getApplication(),adminUsers.class));
                        finishAfterTransition();
                        drawerLayout.closeDrawer(GravityCompat.START);
                        item.setChecked(true);
                        break;
                    case R.id.nav_adminAppointment:
                        item.setChecked(true);
                        drawerLayout.closeDrawer(GravityCompat.START);
                        break;
                    case R.id.nav_adminOnlinePayment:
                        startActivity(new Intent(getApplication(),adminOnlinePayments.class));
                        drawerLayout.closeDrawer(GravityCompat.START);
                        finishAfterTransition();
                        break;
                    case R.id.nav_adminSettings:
                        startActivity(new Intent(getApplication(),adminSettings.class));
                        drawerLayout.closeDrawer(GravityCompat.START);
                        finishAfterTransition();
                        break;
                }

                return true;
            }
        });


    }

    private void getAllBooks() {
        DatabaseReference mDatabase =FirebaseDatabase.getInstance().getReference("Bookings");

        FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
        DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Bookings").child("bookingDetails");

        ref.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                bookingsList.clear();
                for(DataSnapshot ds : snapshot.getChildren()){
                    Bookings bookings = ds.getValue(Bookings.class);
                    if(!bookings.getName().equals(firebaseUser.getDisplayName())){
                        bookingsList.add(bookings);
                    }

                    appointmentAdapter = new AppointmentAdapter(getApplication(), bookingsList);
                    recyclerView.setAdapter(appointmentAdapter);
                    recyclerView.setVisibility(View.VISIBLE);


                }
            }

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

            }
        });
    }
}

CodePudding user response:

That's not how you should filter Realtime Database records. If you download the entire bookingDetails node and filter the data on the client, please note that actually downloading unnecessary data. This practice can be considered a waste of resources and bandwidth. To get, for example, only the booking details that correspond to October, then you should perform a query that will return only the records that have the month field set to "9". So please use the following lines of code:

DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference bookingDetailsRef = db.child("Bookings").child("bookingDetails");
Query queryByMonth = bookingDetailsRef.orderByChild("month").equalTo("9");
queryByMonth.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DataSnapshot> task) {
        if (task.isSuccessful()) {
            for (DataSnapshot ds : task.getResult().getChildren()) {
                Bookings bookings = ds.getValue(Bookings.class);
                Log.d("TAG", bookings.getName());
            }
        } else {
            Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
        }
    }
});

The result in the logcat will be:

Dale Allen Bondoc Liwanag
  • Related