如何在 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中文網其他相關文章!