Bagaimana untuk Mendapatkan Produk Rawak Unik dalam 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 ......................
Cabaran :
Anda mahu memaparkan hanya satu produk rawak unik kepada pengguna, mengelakkan keperluan untuk memuat turun semua produk.
Penyelesaian 1: Pendekatan Klasik
<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>
Penyelesaian 2: Pendekatan Nyahnormalisasi
<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>
Atas ialah kandungan terperinci Bagaimana untuk Memaparkan Produk Rawak Unik daripada Firebase Tanpa Memuat Turun Semua Data?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!