How can I return an object that I create in my data service class through Firebase?
You are confusing your grabUserData
function return value with the Firebase closure return value — the former is User
but the latter is Void
;)
You are actually returning from this closure
— I'm now using a explicit return type to be clear:
{
(snapshot) -> Void in
if let userDict = snapshot.value as? Dictionary<String,String> {
let user = User(
first: userDict["firstName"]!,
last: userDict["lastName"]!,
username: userDict["username"]!
)
return user
}
}
which is passed as the last argument to the observeSingleEvent
Firebase function. This is a very common mistake ;)
Completion handler. A standard pattern here is to return the desired User
via a completion handler instead. This solution nicely models the asynchronous nature of network requests such as Firebase database calls. For instance:
func grabUserData(completion: @escaping (User?) -> Void) {
REF_USERS.child(getCurrentUID()).observeSingleEvent(of: .value) {
(snapshot) in
if let userDict = snapshot.value as? Dictionary<String, String> {
let user = User(
first: userDict["firstName"]!,
last: userDict["lastName"]!,
username: userDict["username"]!
)
completion(user) // Returns user!
} else {
completion(nil) // User not found!
}
}
}
Finally, in your data service client code, call it like this:
grabUserData() {
(user) in
if let user = user {
print("Grabbed user: \(user)")
} else {
print("User not found!")
}
}
How to retrieve an object from firebase database?
I think this may come from the fact that your field is called fdName
, while the property in the database is called foodName
.
Firebase uses either the getter and setter to determine the name of the property, or if those are missing, the name of the field. So it's looking for a property called fdName
in the database.
The solution is to rename your field to match the property name in the database:
public class FoodItem {
private String foodName; // br> private String amount;
public FoodItem(String foodName, String foodAmount) {
this.foodName = foodName;
this.amount=foodAmount;
}
public String getFoodName() {
return this.foodName; // br> }
public String getAmount() {
return this.amount;
}
}
How can I retrieve an object from the Firebase RealTime Database if it contains a List?
I've adapted the answer Frank and Alex mentioned in their comments. And it seems to be working in your situation. Instead of directly usingsnapshot.getValue(HostPlayer.class);
use a GenericTypeIndicator like this;
pChildEventListener = new ChildEventListener() {
@Override
public void onChildAdded(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
GenericTypeIndicator<HostPlayer> t = new GenericTypeIndicator<HostPlayer>() {};
HostPlayer hostPlayer = snapshot.getValue(t);//I was able to get the list without an error
...
}
...
};
Obtaining data from Firebase and creating an object in Flutter, Dart
This is because data is loaded from Firestore (and pretty much any modern cloud API) asynchronously, because it may take some time before it's available. Instead of blocking your code (and the user) during this time, your main code actually continues to execute. Then when the data is available, your then
block executes.
This is easiest to see if you place some logging in the code, run it, and check its output.
print('Before starting to read from the database');
FirebaseFirestore.instance.collection('MaterialQR')
.doc(document).get()
.then((value) => {
print('got data from the database');
});
print('After starting to read from the database');
The output of this is:
Before starting to read from the database
After starting to read from the database
Got data from the database
This is probably not what you expected, but it explains perfectly why you don't get a result from selectFromFirebase
: the return res
runs before res
is ever set by your then
block.
There is no way to prevent this asynchronous nature of the call. Instead you'll have to accept that calling cloud APIs is asynchronous, and return a Future
from the method and mark is as async
:
Future<MaterialQR> selectFromFirebase(String document) async {
That also means you can use await
in there, so the entire function then becomes:
Future<MaterialQR> selectFromFirebase(String document) async {
try {
var value = await FirebaseFirestore.instance.collection('MaterialQR')
.doc(document).get();
return MaterialQR(
exercises: value['exercises'],
image: value['image'],
name: value['name'],
id: value['id']);
}
catch {
return MaterialQR(exercises: [], image: '', name: '', id: '');
}
}
See also:
- The Flutter documentation on asynchronous operations and futures
- The Flutter codelab on Asynchronous programming: futures, async, await.
How to get Data as Object from Firebase to Service and then to Page correctly (Angularfire + ionic4)?
This should work as expected, the error that you get is because the localData
is indeed undefined
until the data comes from the network.
You have 2 solutions for this:
- Either give
localData
an initial value, so it's no longerundefined
:
export class MypagePage implements OnInit {
localData: Partial<DataObject> = {};
// ...
}
- Put an
ngIf
on the label and just don't display it while the data is not there yet:
<ion-content>
<ion-label *ngIf="localData">{{ localData.id }}</ion-label>
</ion-content>
Android Studio Firebase query search returning object
You need to do this approach in order to get each user password, but instead of saving 0, 1, 2 , 3 i would suggest saving userID as main node for each user, so you can get from the user you need the password , this method instead will get you all the passwords from all the users, replace the autogenerated 0 , 1 , 2 ,3 with mAuth.getCurrentUser().getUid();
logIn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String uid = mAuth.getCurrentUser().getUid();
mRef.child("students").child(uid).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
try {
for(DataSnapshot snap : dataSnapshot.getChildren())
YourPojoClass obj = snap.getValue(YourPojoClass.class);
String password =obj.getPassword();
//here compare your local password inserted in your editText with the one pulled from firebase
}
}catch (Exception ex){
//error
}
}
@Override
public void onCancelled(DatabaseError error) {
//cancelled
}
});
}
remember, YourPojoClass.class will be a class with setters and getters wiht the exact name of your database variables
Exactly this is YourPojo.class
public class Student {
private int ISIC;
private String indeks;
private Meal[] meals;
private String name;
private String password;
}
just remember to do setters and getters for it !
UPDATE !
So , now since you get that key you can access to the data inside it
public void getKey() {
dbStudents = FirebaseDatabase.getInstance().getReference("students");
dbStudents.orderByChild("indeks").equalTo(userName.getText().toString())
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
key = snapshot.getKey();
Student std = snapshot.getValue(Student.class);
String password = std.getPassword();
String name = std.getName();
//... And so on with the other data
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
How can I return a value from firebase in Android?
Define an interface:
interface FoodListener {
void onFoodReceived(FoodItem foodItem);
void onError(Throwable error);
}
Then modify your method:
public void getFoodItem(String foodNum, final FoodListener listener) {
dbReference=firebaseDatabase.getReference("Food"+foodNum);
dbReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
FoodItem foodItem = dataSnapshot.getValue(FoodItem.class);
Log.d("h", "Gotdata" + foodItem.getImage());
listener.onFoodReceived(foodItem);
}
@Override
public void onCancelled(DatabaseError databaseError) {
listener.onError(databaseError.toException());
}
});
}
Now, callers of the getFoodItem()
method can pass a listener that will be called either when the food is retrieved or when an error occurs.
Firebase getValue(Class.class) Object
{Name=Bob, Val= x}
doesn't match your object.
Case matters.
private String name;
private String value;
Options
1) Update Java object: private String Name, Val;
2) Update Firebase to have name
and value
be the keys.
Related Topics
Swift - Iboutletcollection Equivalent
What Does the Dollar Sign Do in Swift/Swiftui
Can Swift Return Value from an Async Void-Returning Block
How to Detect Which Skspritenode Has Been Touched
Iterate Over Collection Two At a Time in Swift
First Item in a List Is Always Selected
Get a Swift Variable'S Actual Name as String
How to Disable Pasting in a Textfield in Swift
Deleting a Row from a Uitableview in Swift
Calling a Swift Class Factory Method With Leading Dot Notation
Passing Lists from One Function to Another in Swift
Swiftui Hstack With Wrap and Dynamic Height
How to Get the Count of a Swift Enum
Structure VS Class in Swift Language
How to Save and Read Array of Array in Nsuserdefaults in Swift