简体   繁体   中英

Update item in Firebase Android

i have a list of birthdays and if the birthday is over it should add a year(in milliseconds) to that item on firebase. The main problem im having is that how to access the exact item to add the year. Firebase items werent added through the app thats why i cant use the getKey. Here are the pictures.

if(daysLeft<0){
     mFirebaseDatabaseReference.child(CODEFROGDB).child(/*here i need to get to the item*/).child("bday_p").setValue(model.getBday_p() + 31556952000L);
}

Firebase数据库图片

You can use the previous value to query for the item to be updated:

if(daysLeft<0){
     mFirebaseDatabaseReference.child(CODEFROGDB)
            .orderByChild("bday_p")
            .equalTo(model.getBday_p())
            .addListenerForSingleValueEvent(new ValueEventListener(){

                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    mFirebaseDatabaseReference.child(CODEFROGDB)
                    .child(dataSnapshot.getKey())
                    .child("bday_p").setValue(model.getBday_p() + 31556952000L);
                }

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

The simples way in which you can achieve this, is using the following code:

if(daysLeft<0) {
    mFirebaseDatabaseReference.child(CODEFROGDB)
        .addListenerForSingleValueEvent(new ValueEventListener(){
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                long now = System.currentTimeMillis();
                for(DataSnapshot ds : dataSnapshot.getChildren()) {
                    Long bday_p = ds.child("bday_p").getValue(Long.class);
                    if(bday_p < now) {
                        ds.child("bday_p").getRef().setValue(bday_p + 31556952000L);
                    }
                }
            }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM