如何在单击按钮时从 firebase 获取第一个和最后一个数据

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

我有两个菜单选项 'latest & first' 顾名思义,当我单击最新时,我想从 firebase 获取最新数据,如果我先单击,我想获取第一个数据

这是数据库的截图

所以当我首先说时,我想获取列表中的第一个数据 (q1)

这是我想要实现的方法

 @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() {
        
    }

这里是数据库引用

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

            }

根据您上次的评论,由于您需要单独调用,例如要获取 第一个 问题,请使用以下代码行:

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!
            }
        }
    });
}

logcat 中的结果将是:

The unexamined life is not worth living.

要获取 last 元素,只需使用与上面完全相同的代码,但不能使用 .limitToFirst(1),而必须使用 .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!
            }
        }
    });
}