点击菜单按钮时从Firebase获取首条与最新数据的实现方法
实现方法
首先先修正你现有监听逻辑的问题:当前onDataChange回调里没有清空旧列表,每次数据更新都会重复往quotes_list里添加元素,导致索引计算错误,先把这部分逻辑调整正确:
databaseReference = FirebaseDatabase.getInstance().getReference("Quotes"); model = new Model(); quotes_list = new ArrayList<>(); databaseReference.addValueEventListener(new ValueEventListener() { @SuppressLint("SetTextI18n") @Override public void onDataChange(@NonNull @NotNull DataSnapshot snapshot) { quotes_list.clear(); for (DataSnapshot dataSnapshot1 : snapshot.getChildren()) { model = dataSnapshot1.getValue(Model.class); if (model != null) { quotes_list.add(model.getTitle()); } } if (!quotes_list.isEmpty()) { position = randomQ.nextInt(quotes_list.size()); quotesTxt.setText(quotes_list.get(position)); countTxt.setText((position + 1) + "/" + quotes_list.size()); } } @Override public void onCancelled(@NonNull DatabaseError error) { Log.e("Firebase", "Load quotes failed", error.toException()); } });
推荐方案:复用本地缓存数据
你初始化时已经全量加载了Quotes节点下的所有数据,点击菜单时直接操作本地列表即可,不需要重复发起网络请求,响应速度更快:
private void latestQuote() { if (quotes_list.isEmpty()) return; // 按q1、q2、q3...的key顺序,列表最后一项就是最新节点 position = quotes_list.size() - 1; quotesTxt.setText(quotes_list.get(position)); countTxt.setText((position + 1) + "/" + quotes_list.size()); } private void firstQuote() { if (quotes_list.isEmpty()) return; // 列表第一项就是q1对应的首条数据 position = 0; quotesTxt.setText(quotes_list.get(position)); countTxt.setText((position + 1) + "/" + quotes_list.size()); }
可选方案:实时拉取服务端数据
如果需要每次点击都同步服务端最新状态(比如多端修改数据的场景),可以通过Firebase查询直接拉取对应节点:
private void latestQuote() { // 按key倒序取1条,即为key最大的最新节点 databaseReference.orderByKey().limitToLast(1) .addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { for (DataSnapshot ds : snapshot.getChildren()) { Model latest = ds.getValue(Model.class); if (latest != null) { position = quotes_list.size() - 1; quotesTxt.setText(latest.getTitle()); countTxt.setText((position + 1) + "/" + quotes_list.size()); } } } @Override public void onCancelled(@NonNull DatabaseError error) { Log.e("Firebase", "Load latest quote failed", error.toException()); } }); } private void firstQuote() { // 按key正序取1条,即为q1对应的首条数据 databaseReference.orderByKey().limitToFirst(1) .addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { for (DataSnapshot ds : snapshot.getChildren()) { Model first = ds.getValue(Model.class); if (first != null) { position = 0; quotesTxt.setText(first.getTitle()); countTxt.setText("1/" + quotes_list.size()); } } } @Override public void onCancelled(@NonNull DatabaseError error) { Log.e("Firebase", "Load first quote failed", error.toException()); } }); }
补充说明:如果你的数据不是按
q+递增数字的规则命名key,而是通过时间戳字段排序,把上述查询里的orderByKey()替换为orderByChild("存储时间戳的字段名")即可。
内容的提问来源于stack exchange,提问作者user18105926
相关产品推荐
相关产品推荐

