Read Data Firebase Assign Value

Read Data Firebase assign value

This issue is that Firebase is asynchronous so you need to give Firebase time to fetch and return the requested data. i.e. the data is only valid within the closure.

Your code is assigning values with let items = ... outside the closure and that code will execute way before the data is returned. Move the assignment inside like closure like this (code is shortened for brevity)

func fetchDevies() {
let ref = Database.database().reference().child("some_node").child("Rooms")
ref.observeSingleEvent(of: .value, with: { snapshot in
let value = snapshot.value as? NSDictionary

if let deviceRooms1 = value?["Rooms1"] as? String {
self.deviceRoom1 = deviceRooms1
}
.
.
.
let items = [self.deviceRoom1, self.deviceRoom2, self.deviceRoom3, self.deviceRoom4, self.deviceRoom5]
print(items)
})

//code here will run before Firebase has returned data and populated the vars

Also, be careful with var names. If you are accessing a class var, always refer to it with self. like self.deviceRoom1

read data from firebase and set the value of textview

First, your Database Reference returns you a list of data so you need to receive your data as a list.

Second, if you want to filter your data base on enrollment then add a query in your database reference.

    DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
Query query = databaseReference.child("Marks").orderByChild("enrollment").equalTo(66);

query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot data: dataSnapshot.getChildren()){
String mm=data.child("mcad").getValue().toString();
String jm=data.child("java").getValue().toString();
String nm=data.child("nma").getValue().toString();

txtmcadmarks.setText(nm);
}
}

@Override
public void onCancelled(@NonNull DatabaseError databaseError) {

}
});

Read from firebase database and store the data, return values to be used in other pages

Did the following and got results,


var usr = firebase.auth().currentUser;
var usrId = usr.uid;
var ref = firebase.database().ref('users/' + usrId)

var latestSnapshot = null;
ref.on('value', function(snap) { latestSnapshot = snap.val(); });

export default latestSnapshot````

How to get a value from Firebase Database and assign it to a value in Firebase Cloud Functions?

You are very close to getting the database query to work.

Take a look at the Firebase Documentation. It explains how to access the structured data.

exports.connectMe = functions.https.onRequest((req, res) => {
cors(req, res, () => {
const callRef = admin.database().ref('calls/' + req.body.id + '/').set({
target: req.body.target,
caller: req.body.caller,
time: req.body.time
});

const target = req.body.target;
console.log(`target: ${target}`);

const takenRef = admin.database().ref(`tokens/${target}/token`)
.once('value');

Promise.all([callRef, takenRef])
.then(results => {
const snapshot = results[1]; // Promise of `takenRef`
console.log(snapshot.val()); // This is the data from the database...

res.status(200).send("Thanks For The Call!");
});
});
});

See the updated code, I've added .once('value').then(snapshot onto your query which gives you access to the data.

how to retrieve data from fire base and assign to a string

    DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();

mDatabase.child("menu").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {

//This will loop through all items. Add variables to arrays or lists as required
for (DatasnapShot snap : dataSnapshot.getChildren())
{
foodname = dataSnapshot.child("name").getValue().toString();
String prize = dataSnapshot.child("prize").getValue().toString();
}


}

@Override
public void onCancelled(DatabaseError databaseError) {
}
});

You can fetch each child individually like such. Or you can make use of a Model or a Hashmap to fetch all of the data and then fetch the data you would like based on the Key

Retrieving Firebase data and assigning it to variables

I assume you are asking about how you can add items to the Drawer after creation. It is posible, to update, remove and add items to the Drawer even after creation. For more info check here https://github.com/mikepenz/MaterialDrawer#modify-items-or-the-drawer,

Edit:

    AccountHeader header = new AccountHeaderBuilder()
.withActivity(this)
.withHeaderBackground(R.drawable.header)
.withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() {
@Override
public boolean onProfileChanged(View view, IProfile profile, boolean current) {
//Handle Profile changes
return false;
}
})
.build();

Drawer drawer = new DrawerBuilder()
.withActivity(this)
.withToolbar(toolbar)
.withAccountHeader(header)
.addDrawerItems(
new DividerDrawerItem(),
new SecondaryDrawerItem().withName(R.string.drawer_item_settings),
new SecondaryDrawerItem().withName(R.string.drawer_item_about)
)
.withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
@Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
// Handle clicks
return true;
}
})
.build();

//Later
header.addProfile(new ProfileDrawerItem().withIcon(bitmap).withName(name).withEmail(email), 0);

How does this work?

Firebase Realtime Database Allow read/write if string matches an attribute

To send the special key, add a field specialKey to the model.

Basically, check that the model-key specialKey is equal to the database-field specialKey.

The obvious problem with this approach is, that the specialKey of the model is then persisted with every object, there is a suggestion for that below, too.

Note: newData is the incoming model-data.

The code below might point in the right direction. I did not test it and might have made wrong assumptions.

Rule

{
"rules": {
"shops": {
"$shop_id" {
"payload" {
".read": if true,

// OPTION A

".write": "root.child(shops).child($shop_id)
.child(newData.child('specialKey)).exists()"

// OPTION B
//
// Try deleting the secrectKet in the model.
// No idea if this works in real life.
// === seems to be correct for assigning values?

".write": "root.child(shops).child($shop_id)
.child(newData.child('specialKey)).exists()
&& newData.child('specialKey).val() === '' "

},
"specialKey" {
// is READ:false ok to be processed by rule above?
".read": if false,
".write": if false,
}
}
}
}
}

Data Structure

{
"shops": {
"shop-a": {
"payload": "yourPayload",
"SuperSecretSpecialKey123": true
}
}
}

Source

https://firebase.google.com/docs/rules/rules-language#building_conditions

Bottom Line

It might be worth considering a normal authentication process, then one could assign users write-roles and user proper authentication.

React native firebase how to assign value when getting data from db

Do whatever you want to do inside the callback

var foo;
firebase
.database()
.ref(`/topics/lec1`)
.once("value")
.then(function(snapshot) {
foo = snapshot.val();
displayValue();
});

function displayValue() {
//use value from firebase via foo.
}


Related Topics



Leave a reply



Submit