Buscar..


Comprender a qué datos hace referencia getReference ()

En este ejemplo, usamos esta base de datos:

"your-project-name" : {
    "users" : {
        "randomUserId1" : {
            "display-name" : "John Doe",
            "gender" : "male"
        }
        "randomUserId2" : {
            "display-name" : "Jane Dae",
            "gender" : "female"
        }
    },
    "books" {
        "bookId1" : {
            "title" : "Adventure of Someone"
        },
        "bookId1" : {
            "title" : "Harry Potter"
        },
        "bookId1" : {
            "title" : "Game of Throne"
        }
    }
}

Si usa la base de datos anterior, entonces:

  • FirebaseDatabase.getInstance().getReference()

    apuntará a los datos principales de su proyecto, "your-project-name" . Por lo tanto, el dataSnapshot que adquirió contendrá todos los datos que contiene, incluidos todos los datos de "users" y datos de "books" .

  • FirebaseDatabase.getInstance().getReference("users") y FirebaseDatabase.getInstance().getReference().child("users")

    tendrá el mismo resultado, apuntando a "your-project-name/users"

  • FirebaseDatabase.getInstance().getReference("users/randomUserId1") y FirebaseDatabase.getInstance().getReference().child("users/randomUserId1") y FirebaseDatabase.getInstance().getReference().child("users").child("randomUserId1")

    tendrá el mismo resultado, apuntando a "your-project-name/users/randomUserId1"

Nota: este ejemplo es necesario para comprender completamente qué datos están dentro del objeto dataSnapshot

Entender qué datos están dentro del objeto dataSnapshot

Nota: primero debe saber a qué datos hace referencia getReference () antes de poder comprender completamente este ejemplo.

Existen tres métodos comunes para obtener sus datos de Firebase Realtime Database:

  • addValueEventListener()
  • addListenerForSingleValueEvent()
  • addChildEventListener()

Cuando hablamos sobre qué datos están dentro del objeto dataSnapshot , entonces addValueEventListener() y addListenerForSingleValueEvent() son básicamente lo mismo. La única diferencia es que addValueEventListener() escucha los cambios realizados en los datos a los que se hace referencia, mientras que addListenerForSingleValueEvent() no lo es.


Así que consideremos que tenemos esta base de datos:

"your-project-name" : {
    "users" : {
        "randomUserId1" : {
            "display-name" : "John Doe",
            "gender" : "male"
        }
        "randomUserId2" : {
            "display-name" : "Jane Dae",
            "gender" : "female"
        }
    },
    "books" {
        "bookId1" : {
            "title" : "Adventure of Someone"
        },
        "bookId1" : {
            "title" : "Harry Potter"
        },
        "bookId1" : {
            "title" : "Game of Throne"
        }
    }
}

DataSnapshot producido por addValueEventListener y addListenerForSingleValueEvent

dataSnapshot producido por addValueEventListener() y addListenerForSingleValueEvent() contendrá valores de los datos exactos a los que se hace referencia. Al igual que cuando ref es punto a "your-project-name" entonces dataSnapshot debería ser:

... onDataChange(DataSnapshot dataSnapshot) {
    dataSnapshot.getKey(); // will have value of String: "your-project-name"
    for (DataSnapshot snapshot : dataSnapshot) {
        snapshot.getKey(); // will have value of String: "users", then "books"
        for (DataSnapshot deeperSnapshot : dataSnapshot) {
            snapshot.getKey();
            // if snapshot.getKey() is "users", this will have value of String: "randomUserId1", then "randomUserId2"
            // If snapshot.getKey() is "books", this will have value of String: "bookId1", then "bookId2"
        }
    }
}

DataSnapshot producido por addChildEventListener

dataSnapshot producido por addChildEventListener() contendrá valores de datos un nivel más profundo dentro de los datos a los que se hace referencia. Como en estos casos:

Cuando ref es punto a "your-project-name" entonces dataSnapshot debería ser:

... onChildAdded(DataSnapshot dataSnapshot, String s) {
    dataSnapshot.getKey(); // will have value of String: "users", then "books"
    for (DataSnapshot snapshot : dataSnapshot) {
        snapshot.getKey();
        // if dataSnapshot.getKey() is "users", this will have value of String: "randomUserId1", then "randomUserId2"
        // If dataSnapshot.getKey() is "books", this will have value of String: "bookId1", then "bookId2"
        for (DataSnapshot deeperSnapshot : dataSnapshot) {
            snapshot.getKey();
            // if snapshot.getKey() is "randomUserId1" or "randomUserId1", this will have value of String: "display-name", then "gender"
            // But the value will be different based on key
            // If snapshot.getKey() is "books", this will have value of String: "title", but the value will be different based on key
        }
    }
}
// dataSnapshot inside onChildChanged, onChildMoved, and onChildRemoved will have the same data as onChildAdded

Lo más probable es que queramos usar .getValue() lugar de getKey() . Pero aquí utilizamos getKey porque siempre contendrá una cadena y no será necesario convertirlo en un objeto personalizado, un mapa u otro. Básicamente, cuando sabes a qué clave está apuntando dataSnapshot , puedes saber fácilmente qué valor contiene y analizarlo en tu propio objeto personalizado (o cualquier cosa)



Modified text is an extract of the original Stack Overflow Documentation
Licenciado bajo CC BY-SA 3.0
No afiliado a Stack Overflow