how can i read firebase realtime database?
You're importing the new v9 functions, but in your code you are then trying to use the older syntax. You'll have to pick one or the other.
In v9 syntax, the ref.on("value"
would be:
import { onValue } from "firebase/database";
...
onValue(ref, (pixel) => {
console.log("read")
}
Also see the Firebase documentation on reading from the Realtime Database with the v9 SDK.
Read Data From Firebase database
Ok, I got it sorted out. the above code in the question is perfectly fine and should work .
I am explaining for later users who might have the same issue due to mistakes which I made.
the singleSnapshot.getValue(User.class); was unable to cast the result to user class because when uploading the data i.e. in setValue I had my
photoUrl equal to null and as a result you can see the photoUrl is not present in my child node. So what I believe is (and maybe someone want correct me on this) that my singleSnapshot.getValue method was unable to cast the result.
So for now I have omitted photoUrl from my User class and will get back to it when I will start working withe relevant module.
Thanks again everyone for all the suggestions and help.
public class User {
String name;
Uri photoURL;
String bloodGroup;
String city;
String country;
double latitude;
double longitude;
boolean availableToDonate;
// Get, set and constructors are obvious here I am just saving some space in the post
}
How to read, write and query data in Firebase Realtime Database using Firebase SDK v9 (Modular)
Disclaimer: The v9 modular SDK is a beta release. The syntax may (or may not) change but I'll try to update the answer if any asap. Benefits of this upgrade can be found here.
The modular SDK cannot be used over CDN and you need to use npm or yarn for the time being. I've tested this in a Vue web-app.
1. Initialize the Firebase App:
import { initializeApp } from "firebase/app";
const firebaseConfig = {
apiKey: "<api-key>",
authDomain: "<project-id>.firebaseapp.com",
databaseURL: "https://<project-id>.firebaseio.com",
projectId: "<project-id>",
storageBucket: "<project-id>.appspot.com",
messagingSenderId: "0000000000",
appId: "<app-id>",
}
const app = initializeApp(firebaseConfig)
2. Create a Database Instance and Reference:
import { getDatabase, ref } from "firebase/database"
const db = getDatabase(app) // <-- Pass in the initialized app
//Creating the reference (The path in db you are trying to read/write/update)
const dbRef = ref("/users")
3. Read Operation and Listeners:
You need to use get()
method to retrieve data which accepts a query as parameter. If you are simply reading the data without any sorting or filtering, just pass the reference created above in the query()
. (Note: Passing the reference directly in get() works in this case)
import { get, query, onValue } from "firebase/database"
const usersSnapshot = await get(query(dbRef)) //This should get the whole users node from db.
//To add a listener you can use the onValue() method like,
onValue(query(dbRef), snapshot => {
console.log(snapshot.val())
})
//
In v8, the syntax for events looks like .on("event_name")
. In v9, all events are a method which can be used this way:
import { onChildAdded, onChildChanged, onChildRemoved } from "firebase/database"
onChildAdded(query(dbRef), (snapshot) => {
console.log("child added");
console.log(snapshot.val()); // Logs newly added child
});
onChildChanged(query(dbRef), (snapshot) => {
console.log("child changed")
console.log(snapshot.val()); // Logs updated value of changed child
});
onChildRemoved(query(dbRef), (snapshot) => {
console.log("child removed");
console.log(snapshot.val()); // Logs value of removed child
});
4. Writing Data:
// You maybe have figured out the upgrade trend ¯\_(ツ)_/¯
import { set, update } from "firebase/database"
const newUserName = "user1122"
const userRef = ref(`users/${newUserName}`)
await set(userRef, {name: newUserName, age: 11})
await update(userRef, {age: 12})
5. Working with lists:
This is best part and it now kind of feels similar to adding stages in a MongoDB Aggregation.
import { query, orderByChild, orderByValue, orderByKey, limitToLast } from "firebase/database"
//Example: getting 3 youngest users from the db
const usersSnapshot = await get(query(dbRef, ...[orderByChild("age"), limitToFirst(3)]))
The first parameter in the query()
is the Database Reference and all following parameters are QueryConstraints and can be either of these methods: 'endAt' | 'endBefore' | 'startAt' | 'startAfter' | 'limitToFirst' | 'limitToLast' | 'orderByChild' | 'orderByKey' | 'orderByPriority' | 'orderByValue' | 'equalTo';
. You can pass them as individual parameters instead of using spread operator as I've used.
I've found no issues using the modular SDK so far. Just make sure you've imported all things which are needed.
PS: Just in-case if you use Vue, React or any framework with hot-reload when developing, you might encounter the "Firebase App named '[DEFAULT]' already exists (app/duplicate-app)" error. Checking if firebase.apps.length
is 0 helps and that's done this way in modular SDK:
import { getApps, initializeApp } from "firebase/app"
if (!getApps().length) initializeApp(firebaseConfig)
How to read data from Firebase Database? - Java
To be able to read the data under the jjjj
node, please use the following lines of code:
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference nameRef = db.child("players").child("jjjj");
nameRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
DataSnapshot snapshot = task.getResult();
String loses = snapshot.child("loses").getValue(Long.class);
String name = snapshot.child("name").getValue(String.class);
String wins = snapshot.child("wins").getValue(Long.class);
Log.d("TAG", loses + "/" + name + "/" + wins);
} else {
Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
}
}
});
The result in the logcat will be:
3/jjjj/4
Things to notice:
- Always create a reference that points to the node that you want to read.
- If your database is located in another lcoation than the default, check this answer out.
firebase realtime database, how to read only own data?
If the keys directly under notifications
are the Firebase Authentication UIDs (as your rules suggest), you can limit access to only the user's node with:
{
"rules": {
//".read": "auth != null", // Remove this line
".write": false,
"notifications":{
"$user_id":{
".read": "auth.uid === $user_id", // add this line
".indexOn":"createdAt"
}
}
}
}
Also see the Firebase documentation on securing content-owner only access.
How to Read Data From Firebase Realtime Database?
The error seems pretty clear. You're calling var keys = snap.value.keys;
and there is no keys
on the snap.value
. From this, it seems that you think snap.value
is a Map
object, which doesn't seem to be the case.
From looking at your data structure, it is more likely that snap.value
is actually a List
object.
This is because Firebase interprets objects with sequential, numeric keys are arrays. If this is indeed the case (something you can easily verify by running the code in a debugger), you can iterate over the list with:
for (var child in snap.value){
Also see:
- Best Practices: Arrays in Firebase.
Related Topics
How to Stop an Infinitely Rotating Image? and How Does One Implement Removeallanimations
Image Disappears When Styling Class to Make a Round Image
How to Call a Func Within a Closure
Tabview, Tabitem: Running Code on Selection or Adding an Ontapgesture
Generic Class with Class-Bound Constraint Cannot Be Parametrized by Class-Bound Protocol
App Window on Top of All Windows Including Others App Windows
How to Sort an Array of Posts by Their Elements
Swift Uikit Dynamics Add Collision Boundary. After Rotation Does Not Work Correctly
Spritekiit Swift: Touch a Moving Object
Finding All Types That Conform to a Protocol
Passing Unknown Number of Arguments in a Function
How to Set Cadisplaylink in Swift with Weak Reference Between Target and Cadisplaylink Instance
Swift: Implementing Protocol Initializer in a Class
C++ Dylib in Swift Project - Undefined Symbols for Function Exposed in Dylib
Using Tvposterimage in Tvuikit for Tvos 12
Ambiguous Method Overload with Closures in Swift, But Only When Closure Returns a Value