如何在 Node Firebase 中获取唯一的随机乘积?
数据:
- products - -L74Pc7oVY22UsCETFBv - name: "gjwj" - category: "hreggrrg" - location: "vjhiwehifwe" - price: 44 - color: fassaf - -L74uJ7oVYcVNyCteFBz - name: "uygfwh" - category: "hhhjwwwom" - location: "pervrr" - price: 33 - color: yrtrr ......................
挑战:
您只想向用户显示一种唯一的随机产品,避免需要下载所有产品。
解决方案 1:经典方法
<code class="java">DatabaseReference productsRef = rootRef.child("products"); ValueEventListener valueEventListener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { List<String> productList = new ArrayList<>(); for(DataSnapshot ds : dataSnapshot.getChildren()) { String name = ds.child("name").getValue(String.class); productList.add(name); } int productListSize = productList.size(); List<String> randomProductList = new ArrayList<>(); randomProductList.add(new Random().nextInt(productListSize)); //Add the random product to list // Update the adapter with the random product arrayAdapter.notifyDatasetChanged(); } @Override public void onCancelled(DatabaseError databaseError) { Log.d(TAG, "Error: ", task.getException()); //Don't ignore errors! } }; productsRef.addListenerForSingleValueEvent(valueEventListener);</code>
解决方案2:反规范化方法
<code class="java">DatabaseReference productIdsRef = rootRef.child("productIds"); ValueEventListener valueEventListener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { List<String> productIdsList = new ArrayList<>(); for(DataSnapshot ds : dataSnapshot.getChildren()) { String productId = ds.getKey(); productIdsList.add(productId); } int productListSize = productList.size(); String randomProductId = productIdsList.get(new Random().nextInt(productListSize)); DatabaseReference productIdRef = rootRef.child("products").child(randomProductId); ValueEventListener eventListener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { String name = dataSnapshot.child("name").getValue(String.class); Log.d("TAG", name); // Output the random product name } @Override public void onCancelled(DatabaseError databaseError) { Log.d(TAG, "Error: ", task.getException()); //Don't ignore errors! } }; productIdRef.addListenerForSingleValueEvent(eventListener); } @Override public void onCancelled(DatabaseError databaseError) { Log.d(TAG, "Error: ", task.getException()); //Don't ignore errors! } }; productIdsRef.addListenerForSingleValueEvent(valueEventListener);</code>
以上是如何在不下载所有数据的情况下显示 Firebase 中的独特随机产品?的详细内容。更多信息请关注PHP中文网其他相关文章!