0

I'm having a problem when I try to star a movie which id doesn't exist in my likes firebase node. Here's my code:

private void onStarClicked(long releaseId, final String uid) {
    final DatabaseReference postRef = ((GamePageActivity)getActivity()).mDatabaseRef.child("likes").child(mRegion).child(String.valueOf(releaseId));
    postRef.runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            _Post p = mutableData.getValue(_Post.class);
                            if (p == null) {
                Log.d(TAG, "Transaction success");
                return Transaction.success(mutableData);
            }

            if (p.stars.containsKey(uid)) {
                // Unstar the post and remove self from stars
                p.starCount = p.starCount - 1;
                p.stars.remove(uid);
            } else {
                // Star the post and add self to stars
                p.starCount = p.starCount + 1;
                p.stars.put(uid, true);
            }

            // Set value and report transaction success
            mutableData.setValue(p);
            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b,
                               DataSnapshot dataSnapshot) {
            // Transaction completed
            Log.d(TAG, "postTransaction:onComplete:" + databaseError);
        }
    });
}

The problem is if my id "releaseId" doesn't exist in the database, the star won't get added in, I thought my code was supposed to first add the "releaseId" if it doesn't exist?

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193

1 Answers1

0

It seems a bit complicated to try to add a movie inside your likes path during a ‘like’ transaction. Ideally, it would already be there. So it will be easier to separate adding the movie to the likes path, and after that use a Cloud Function onCreate or onUpdate.

I assume you have your movie data somewhere else in your database. Let’s call it the ‘movies’ path for now. One idea to try is to have a Cloud Function that watches your ‘movies’ path, and when a movie is added, the function will add that movie data to your ‘likes’ path. That way, once a user tries to like a movie, its information is already in the correct spot in the database. Fixing the problem of the non-existent 'releaseId'.

Firebase Realtime Database Triggers

If you don’t want to use a Cloud Function, you can consider writing to both the ‘movies’ path and ‘likes’ path directly from the client when the movie is added, to accomplish the same thing.