How to Get a Unique Random Product in Node Firebase?
Data:
- products - -L74Pc7oVY22UsCETFBv - name: "gjwj" - category: "hreggrrg" - location: "vjhiwehifwe" - price: 44 - color: fassaf - -L74uJ7oVYcVNyCteFBz - name: "uygfwh" - category: "hhhjwwwom" - location: "pervrr" - price: 33 - color: yrtrr ......................
Challenge:
You want to display only one unique random product to the user, avoiding the need to download all the products.
Solution 1: Classic Approach
<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>
Solution 2: Denormalization Approach
<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>
The above is the detailed content of How to Display a Unique Random Product from Firebase Without Downloading All Data?. For more information, please follow other related articles on the PHP Chinese website!