Home > OS >  How to get the first and the last data from firebase on button click
How to get the first and the last data from firebase on button click

Time:06-03

I have two menu option 'latest & first' as the name suggest when I click the latest I want to get the latest data from firebase and if I click first I want to get the first data

here is a screenshot of how the database looks enter image description here

so when I say first I want to get the first data in the list (q1)

here is the method by which I want to implement this

 @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menue, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.latestQuote:
                latestQuote();
                return true;
            case R.id.firstQuote:
                firstQuote();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void latestQuote() {
    }

    private void firstQuote() {
        
    }

here is the database refrence

databaseReference = FirebaseDatabase.getInstance().getReference("Quotes");
        model = new Model();
        quotes_list = new ArrayList<>();
        databaseReference.addValueEventListener(new ValueEventListener() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onDataChange(@NonNull @org.jetbrains.annotations.NotNull DataSnapshot snapshot) {
                for (DataSnapshot dataSnapshot1 : snapshot.getChildren()) {
                    model = dataSnapshot1.getValue(Model.class);
                    if (model != null) {
                        quotes_list.add(model.getTitle());
                        position = randomQ.nextInt(quotes_list.size());

                    }
                }
                quotesTxt.setText(quotes_list.get(position));
                countTxt.setText(position   "/"   quotes_list.size());

            }

CodePudding user response:

According to your last comment, since you need to have separate calls, for example, to get the first question, please use the following lines of code:

private void firstQuote() {
    DatabaseReference db = FirebaseDatabase.getInstance().getReference();
    DatabaseReference quotesRef = db.child("Quotes");
    Query queryForFirstElement = quotesRef.orderByKey().limitToFirst(1); //           
  • Related