Code only retrieving one value from data in Firebase
import UIKit
import FirebaseDatabase
class HomeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// MARK: - variables
var postDB: DatabaseReference!
override func viewDidLoad() {
super.viewDidLoad()
// getting a node from database //
postDB = Database.database().reference().child("Posts")
// observing data changes //
postDB.observe(DataEventType.value) { (dataSnapshot) in
self.postArray.removeAll()
if dataSnapshot.childrenCount > 0 {
for post in dataSnapshot.children.allObjects as! [DataSnapshot] {
let object = post.value as! [String: Any]
let description = object["description"] as! String
let title = object["title"] as! String
let userName = object["username"] as! String
let model = postStruct(title: title, description: description, username: userName))
self.postArray.append(model)
}
}
self.tableView.reloadData()
}
}
}
How to read only one key to get value from Firebase Database?
FirebaseAuth mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
DatabaseReference myRef = mFirebaseDatabase.getReference().child("user/Harry");
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
User myUser = dataSnapshot.getValue(User.class);
Log.d("FB", myUser.getAddress());
Log.d("FB", myUser.getPhone());
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "onCancelled", databaseError.toException());
}
});
How to read only one value from Firebase Database in Android Studio?
In your case, you just want to retrieve that String ONCE, and not listen for any changes.
So, what you do:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.addListenerForSingleValueEvent(new ValueEventListener(){
@Override
public void onDataChange(DataSnapshot dataSnapshot){
String value = dataSnapshot.child("a1").getValue(String.class); //This is a1
}
});
How to get specific value or row data from firebase in web
Try the following:
firebase.database().ref().child("Students").orderByChild("Email").equalTo("Adnan@gmail.com").once("value", function (snapshot) {
snapshot.forEach(function(childSnapshot) {
var cellNum=childSnapshot.val().CellNum;
});
});
The snapshot is at Students
, then you loop inside the id 22222
and retrieve the CellNum
. The orderByChild
is the query where Email="Adnan@gmail.com"
Retrieve only the Value without the Key in Firebase
Try this
dataSource?.populateCellWithBlock { (cell: UITableViewCell, obj: NSObject) -> Void in
let snap = obj as! FIRDataSnapshot
let childString = snap.value as! [String : AnyObject]
if let url = childString["url"] as? String {
cell.textLabel?.text = url
} else {
print("No value for url")
}
}
childString variable you are using is a dictionary which has values for keys. You need to fetch the value for the key "url".
How to only get one value of child firebase cloud function?
You will need to resolve promises in order to get the value returned by them. What you are doing at the moment is assigning nama_matkul
the promise but you never wait for it to complete.
Async/Await
You can either use async
/await
by defining your function as asynchronous:
.onCreate(async (snapshot,context) =>{
// Your asynchronous code here
}
You can then resolve the promise by running
const nama_matkul = (await admin.database().ref('/courses/'+course_id_p+'name').once('value')).val();
If you need to handle exceptions, wrap the promise and await in a try catch block.
After refactoring your code, it might look something like this:
export const onNotifPengumuman = functions.database.ref('/pengumuman_course/{course_id_p}/{pengumuman_id}')
.onCreate(async (snapshot,context) => {
try {
const course_id_p = context.params.course_id_p;
const pengumuman_id = context.params.pengumuman_id;
const nama_matkul = (await admin.database().ref('/courses/'+course_id_p+'name').once('value')).val();
console.log(`cobacobacoba ${nama_matkul}`);
const pengumumanData = (await admin.database().ref('pengumuman/' + pengumuman_id + '/').once('value')).val();
const notifDataPengumuman = {
data: {
data_type: "pengumuman ",
title: "Pengumuman Baru", // data bebas (key, value)
body: `${nama_matkul}`, // chatId = const chatId
sound: "default"
}
}
try {
await admin.messaging().sendToTopic(course_id_p, notifDataPengumuman);
console.log("Successfully sent message:", response);
} catch (messageSendError) {
console.log("Error sending message:", messageSendError);
}
} catch (error) {
console.log(error);
}
});
Then/Catch
If you do want to stick with the current setup you have and work with callbacks, you can instead keep the .then
call and handle your application logic in the callback; your code might look something like this:
export const onNotifPengumuman = functions.database.ref('/pengumuman_course/{course_id_p}/{pengumuman_id}')
.onCreate((snapshot,context) => {
const course_id_p = context.params.course_id_p;
const pengumuman_id = context.params.pengumuman_id;
admin.database().ref('/courses/'+course_id_p+'name').once('value')
.then(nameSnapshot => {
const nama_matkul = nameSnapshot.val();
console.log(`cobacobacoba ${nama_matkul}`);
admin.database().ref('pengumuman/' + pengumuman_id + '/').once('value')
.then(dataSnapshot => {
const pengumumanData = dataSnapshot.val();
const notifDataPengumuman = {
data: {
data_type: "pengumuman ",
title: "Pengumuman Baru", // data bebas (key, value)
body: `${nama_matkul}`, // chatId = const chatId
sound: "default"
}
}
return admin.messaging().sendToTopic(course_id_p, notifDataPengumuman)
.then(response => console.log("Successfully sent message:", response))
.catch(error => console.log("Error sending message:", error));
})
.catch(error => console.log(error));
})
.catch(error => console.log(error))
});
You can of course use a combination of then/catch and await if you so wish, whether this is a good practice or when to use which really depends on the situation in which you use it.
How to retrieve values from a Firebase Realtime Database with same fields(only values of that particular field) into a text view in android?
While Sairaj Sawant's answer might work, keep in mind that there is no need to attach a listener at every iteration of the loop. A more convenient solution is to attach a listener only once, like in the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference juneRef = rootRef.child("Reports").child("June");
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String totalIncome = "";
for(DataSnapshot ds : dataSnapshot.getChildren()) {
totalIncome = totalIncome + ds.child("Income").getValue(String.class) + " ";
}
Log.d("TAG", totalIncome);
textView.setText(totalIncome);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore errors!
}
};
juneRef.addListenerForSingleValueEvent(valueEventListener);
This code will work only if the Income
property is of type String, as it is set in your 20-06-2020
child. However, the above code will not work if the value is set as an Integer
as it set in your second 21-06-2020
child. Remember, both types of values must match. You either set both as String and the above code will work, or you set them as numbers, case in which you should use this line:
totalIncome = totalIncome + ds.child("Income").getValue(Long.class) + " ";
Related Topics
iOS 8 Swift Audio Playback Execute Method on Completion
Moving an Object Across the Screen at a Certain Speed.(Sprite Kit)
Generic Class with Class-Bound Constraint Cannot Be Parametrized by Class-Bound Protocol
Replace Multiple Words from a String Based on the Values in an Array
Presenting a Uiviewcontroller from Skscene Shows Black Screen
Prepare for Segue with Array - Xcode 8.0 Swift 3.0
How to Convert [Any] to Nsarray
Finding All Types That Conform to a Protocol
How to Compare Two Strings to Check If They Have Same Characters Swift 4
What Does the Underscore in a Function Declaration Do
Self. in Trailing Swift Closures, Meaning and Purpose
How to Have Either or Wherefields for Firestore Query
Using Tvposterimage in Tvuikit for Tvos 12