2

I'm trying to use firebase database transactions to update a "likes" counter in my database. But when running the transaction, mutable data returns null even though the node clearly exists. Here is my code.

FirebaseDatabase.getInstance().getReference("uploads").child(id)
            .runTransaction(new Transaction.Handler() {
                @Override
                public Transaction.Result doTransaction(MutableData mutableData) {
                    Post p = new Post();
                    if (mutableData.getValue(Post.class) != null) {
                        p = mutableData.getValue(Post.class);
                    } else Log.w("mutableData", "isEmpty");

                    p.setLikes(p.getPoints() + 1);

// Some other code...

I'm not sure why it's returning null. The id clearly exists under the uploads node. What could possibly be the problem and what can I do to solve it?

birukhimself
  • 193
  • 3
  • 14
  • post your post class and the firebase node structure, maybe there is a mismatch – Kushan Mar 26 '18 at 20:52
  • 1
    This is expected behavior: the `mutableData` contains the client's best guess as to the current value of the node. It's initial guess will often be that the node doesn't exist. Just return whatever value the node should become in that case. Once the client has done a roundtrip to the server, it will call your `doTransaction` with a better guess. See https://stackoverflow.com/questions/35818946/firebase-runtransaction-not-working – Frank van Puffelen Mar 27 '18 at 03:36

0 Answers0