Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase updating value for a field in a child

I have a Child in Firebase like this in my ANDROID project:

{
  "posts" : {
    "-KNnbTHJGm83zpSELWwB" : {
      ".priority" : "6gydj46kg0",
      "branch" : "Branch",
      "category" : "Categoria",
      "expiration" : "24h",
      "g" : "6gydj46kg0",
      "l" : [ -23.5415083, -46.88642 ],
      "photo" : "mPostPic_20160728192627.jpeg",
      "price" : 10,
      "priority" : 0,
      "product" : "ipad",
      "userKey" : "BNd8RP5qHoc0q7f9gn8cLjPy5Ux1",
      "offerMessage": "Valido ate as 14:00 hs",
      "likeCount": 0
    }
  }
}

I just need to read the likeCount value and increment it by 1 in specific situation.

I have read a lot of Firebase documentation and sample and most part of examples is related to push data or read data and handle value changed.

I just need to read value, increment, save value again but I am newbie in Firebase and not finding a efficient way to do that.

like image 722
Developer MobileCode Labs Avatar asked Dec 06 '25 18:12

Developer MobileCode Labs


1 Answers

I have splited my Json in 2 files and now the code below is working as i expected.

public void writeUserSawPost(final String postkey, int mode){


        final DatabaseReference mPostsRef = mDatabase.child("posts/" + postkey);
        String user = mAuth.getCurrentUser().getUid();
        final DatabaseReference mPostUser = mDatabase.child("posts-user/" + user + "/" + postkey + "/sentiment");

        if (mode == Constants.LIKE) {



            mPostsRef.runTransaction(new Transaction.Handler() {
                @Override
                public Transaction.Result doTransaction(MutableData mutableData) {
                    Post p = mutableData.getValue(Post.class);
                    if (p == null) {
                        return Transaction.success(mutableData);
                    }
                    p.likeCount = p.likeCount + 1;
                    mutableData.setValue(p);
                    return Transaction.success(mutableData);
                }

                @Override
                public void onComplete(DatabaseError databaseError, boolean b,
                                       DataSnapshot dataSnapshot) {
                    // Transaction completed


                }
            });


            mPostUser.setValue("like");

        } else if (mode == Constants.DISLIKE){
            mPostUser.setValue("dislike");
        }



    }
like image 56
Developer MobileCode Labs Avatar answered Dec 08 '25 10:12

Developer MobileCode Labs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!