Maison  >  Article  >  Java  >  Comment afficher un produit aléatoire unique à partir de Firebase sans télécharger toutes les données ?

Comment afficher un produit aléatoire unique à partir de Firebase sans télécharger toutes les données ?

Susan Sarandon
Susan Sarandonoriginal
2024-10-27 22:27:02971parcourir

 How to Display a Unique Random Product from Firebase Without Downloading All Data?

Comment obtenir un produit aléatoire unique dans Node Firebase ?

Données :

- products
   - -L74Pc7oVY22UsCETFBv
       - name: "gjwj"
       - category: "hreggrrg"
       - location: "vjhiwehifwe"
       - price: 44
       - color: fassaf
   - -L74uJ7oVYcVNyCteFBz
       - name: "uygfwh"
       - category: "hhhjwwwom"
       - location: "pervrr"
       - price: 33
       - color: yrtrr
   ......................

Défi :

Vous souhaitez afficher un seul produit aléatoire unique à l'utilisateur, évitant ainsi d'avoir à télécharger tous les produits.

Solution 1 : Approche classique

  1. Ajoutez child("products") à votre référence pour cibler le nœud correct dans la base de données.
  2. Parcourez tous les nœuds enfants du nœud products.
  3. Ajoutez les noms des produits à une liste.
  4. Obtenez un index aléatoire dans la taille de la liste.
  5. Ajoutez le produit à l'index aléatoire à la randomProductList.
<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 : Approche de dénormalisation

  1. Créez un nouveau nœud appelé productIds dans la base de données.
  2. Ajoutez une clé pour chaque ID de produit sous productIds node.
  3. Interrogez le nœud productIds pour obtenir les ID de produit.
  4. Générez un index aléatoire dans le nombre d'ID de produit.
  5. Interrogez le nœud de produits à l'aide de l'ID de produit aléatoire. pour obtenir les détails du produit.
<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>

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn