0

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());

            }
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193

1 Answers1

0

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); //
    queryForFirstElement.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<DataSnapshot> task) {
            if (task.isSuccessful()) {
                for (DataSnapshot qs : task.getResult().getChildren()) {
                    String title = qs.child("title").getValue(String.class);
                    Log.d("TAG", title);
                    quotes_list.add(title);
                    position = randomQ.nextInt(quotes_list.size());
                }
                quotesTxt.setText(quotes_list.get(position));
                countTxt.setText(position + "/" + quotes_list.size());
            } else {
                Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
            }
        }
    });
}

The result in the logcat will be:

The unexamined life is not worth living.

To get the last element, then simply use the exact code as above, but instead of using .limitToFirst(1), you have to use .limitToLast(1):

private void latestQuote() {
    DatabaseReference db = FirebaseDatabase.getInstance().getReference();
    DatabaseReference quotesRef = db.child("Quotes");
    Query queryForFirstElement = quotesRef.orderByKey().limitToLast(1); //
    queryForFirstElement.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<DataSnapshot> task) {
            if (task.isSuccessful()) {
                for (DataSnapshot qs : task.getResult().getChildren()) {
                    String title = qs.child("title").getValue(String.class);
                    Log.d("TAG", title);
                    quotes_list.add(title);
                    position = randomQ.nextInt(quotes_list.size());
                }
                quotesTxt.setText(quotes_list.get(position));
                countTxt.setText(position + "/" + quotes_list.size());
            } else {
                Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
            }
        }
    });
}
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • Hey thanks for the answer and sorry for replying late too it , Hey actually i want to get the first data and the latest data in there respected method as i shown in the code private void latestQuote() { } private void firstQuote() { } –  Jun 03 '22 at 04:28
  • In that case, please see my updated answer. Is it ok now? – Alex Mamo Jun 03 '22 at 04:31
  • hey please can you see the updated question , i add the code which i use to get data , this is how i want to get the data too –  Jun 03 '22 at 04:31
  • The edited question is not related to the initial question. I just rolled it back to the initial state. In general, other questions that derive from the initial question should be considered new questions and should be added here on StackOverflow separately. – Alex Mamo Jun 03 '22 at 04:34
  • So please post a new question, here on StackOverflow, using its own [MCVE](https://stackoverflow.com/help/mcve), so I and other Firebase developers can help you. – Alex Mamo Jun 03 '22 at 04:35
  • 1
    okay i add a new question just a min –  Jun 03 '22 at 04:36
  • yes actually its not working –  Jun 03 '22 at 04:41
  • "it's not working" doesn't provide enough information so I can further help. What exactly doesn't work? Do you have any errors? – Alex Mamo Jun 03 '22 at 04:45
  • please check what i add http://pastie.org/p/0COrVNSIteAwkbJS2mhXf4 –  Jun 03 '22 at 04:45
  • The code I provided was just an example in which I showed you how to correctly get the title. Having the title you can do whatever you want with it. But I have just updated the answer to use the exact same code as you do. Does it work niow? – Alex Mamo Jun 03 '22 at 05:01
  • But I'm not sure how it will work since the list will always have the size of 1. – Alex Mamo Jun 03 '22 at 05:03
  • just a sec i check and i inform u –  Jun 03 '22 at 05:03
  • uhh no its not working , if u say i can i add the code so you can undertsand a –  Jun 03 '22 at 05:06
  • Your question states "How to get the first and the last data from firebase". So If you try to look at the logcat, are you getting the first and the last question as requested? Please answer this. – Alex Mamo Jun 03 '22 at 05:09
  • okay wait its gettin the first quote but the issue is as we are using position = randomQ.nextInt(quotes_list.size()); its setinng text random quote –  Jun 03 '22 at 05:13
  • In the first method, what does `Log.d("TAG", title);` print out in the logcat? It should print `The unexamined life is not worth living.` if you still have the database schema that exists in the screenshot you have added to your question, right? – Alex Mamo Jun 03 '22 at 05:16
  • okay wait its gettin the first quote but the issue is as we are using position = randomQ.nextInt(quotes_list.size()); its setinng text random quote –  Jun 03 '22 at 05:17
  • its just showing in the logcat but when setText its getting random quote –  Jun 03 '22 at 05:18
  • Good to hear that you got the first quote. Other things that don't work the way you expect, should be added to a different question. So all the logic regarding the part where you want to get a random question should be added to a newer question. Since you're new, I recommend you check [this](https://stackoverflow.com/questions/50413117/how-to-get-unique-random-product-in-node-firebase/50413208) out. – Alex Mamo Jun 03 '22 at 05:19
  • So can I help you with other information regarding the initial question (not other stuff that is related to getting a random question)? – Alex Mamo Jun 03 '22 at 05:21
  • 1
    okay i checked the latest one too and its getting the latest quote in the logcat –  Jun 03 '22 at 05:22
  • 1
    Good to hear that too ;) – Alex Mamo Jun 03 '22 at 05:23
  • 1
    Thank you so much for this big help , yes i will add a new question for not able to get the text , thanks a lot –  Jun 03 '22 at 05:23