com.google.firebase.database.MutableData Java Examples

The following examples show how to use com.google.firebase.database.MutableData. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PostInteractor.java    From social-app-android with Apache License 2.0 6 votes vote down vote up
public void incrementWatchersCount(String postId) {
    DatabaseReference postRef = databaseHelper.getDatabaseReference().child(DatabaseHelper.POSTS_DB_KEY + "/" + postId + "/watchersCount");
    postRef.runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            Integer currentValue = mutableData.getValue(Integer.class);
            if (currentValue == null) {
                mutableData.setValue(1);
            } else {
                mutableData.setValue(currentValue + 1);
            }

            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
            LogUtil.logInfo(TAG, "Updating Watchers count transaction is completed.");
        }
    });
}
 
Example #2
Source File: ProfileInteractor.java    From social-app-android with Apache License 2.0 6 votes vote down vote up
public void updateProfileLikeCountAfterRemovingPost(Post post) {
    DatabaseReference profileRef = databaseHelper
            .getDatabaseReference()
            .child(DatabaseHelper.PROFILES_DB_KEY + "/" + post.getAuthorId() + "/likesCount");
    final long likesByPostCount = post.getLikesCount();

    profileRef.runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            Integer currentValue = mutableData.getValue(Integer.class);
            if (currentValue != null && currentValue >= likesByPostCount) {
                mutableData.setValue(currentValue - likesByPostCount);
            }

            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
            LogUtil.logInfo(TAG, "Updating likes count transaction is completed.");
        }
    });

}
 
Example #3
Source File: SignInActivity.java    From budgetto with MIT License 6 votes vote down vote up
private void runTransaction(DatabaseReference userReference) {
    showProgressView();
    userReference.runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            User user = mutableData.getValue(User.class);
            if (user == null) {
                mutableData.setValue(new User());
                return Transaction.success(mutableData);
            }

            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean committed,
                               DataSnapshot dataSnapshot) {
            if (committed) {
                startActivity(new Intent(SignInActivity.this, MainActivity.class));
                finish();
            } else {
                errorTextView.setText("Firebase create user transaction failed.");
                hideProgressView();
            }
        }
    });
}
 
Example #4
Source File: CommentInteractor.java    From social-app-android with Apache License 2.0 6 votes vote down vote up
public void decrementCommentsCount(String postId, final OnTaskCompleteListener onTaskCompleteListener) {
    DatabaseReference postRef = databaseHelper
            .getDatabaseReference()
            .child(DatabaseHelper.POSTS_DB_KEY + "/" + postId + "/commentsCount");
    postRef.runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            Integer currentValue = mutableData.getValue(Integer.class);
            if (currentValue != null && currentValue >= 1) {
                mutableData.setValue(currentValue - 1);
            }

            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
            LogUtil.logInfo(TAG, "Updating comments count transaction is completed.");
            if (onTaskCompleteListener != null) {
                onTaskCompleteListener.onTaskComplete(true);
            }
        }
    });
}
 
Example #5
Source File: TransactionHandler.java    From gdx-fireapp with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public Transaction.Result doTransaction(MutableData mutableData) {
    try {
        if (mutableData.getValue() == null) {
            mutableData.setValue(transactionFunction.apply((R) DefaultTypeRecognizer.getDefaultValue(dataType)));
            return Transaction.success(mutableData);
        }
        MapConversion mapConversionAnnotation = null;
        R transactionData;
        if (promise.getThenConsumer() != null) {
            mapConversionAnnotation = AnnotationFinder.getMethodAnnotation(MapConversion.class, promise.getThenConsumer());
        }
        if (mapConversionAnnotation != null) {
            transactionData = (R) mutableData.getValue(mapConversionAnnotation.value());
        } else {
            transactionData = (R) mutableData.getValue();
        }
        mutableData.setValue(transactionFunction.apply(transactionData));
        return Transaction.success(mutableData);
    } catch (Exception e) {
        GdxFIRLogger.error(TRANSACTION_ERROR, e);
        return Transaction.abort();
    }
}
 
Example #6
Source File: TransactionHandlerTest.java    From gdx-fireapp with Apache License 2.0 6 votes vote down vote up
@Test
public void doTransaction() {
    // Given
    Function transactionFunction = Mockito.mock(Function.class);
    FuturePromise promise = Mockito.mock(FuturePromise.class);
    TransactionHandler transactionHandler = new TransactionHandler(Long.class, transactionFunction, promise);
    MutableData mutableData = Mockito.mock(MutableData.class);
    Mockito.when(mutableData.getValue()).thenReturn("test_value");

    // When
    transactionHandler.doTransaction(mutableData);

    // Then
    PowerMockito.verifyStatic(Transaction.class, VerificationModeFactory.times(1));
    Transaction.success(Mockito.nullable(MutableData.class));
}
 
Example #7
Source File: CommentInteractor.java    From social-app-android with Apache License 2.0 6 votes vote down vote up
public void decrementCommentsCount(String postId, final OnTaskCompleteListener onTaskCompleteListener) {
    DatabaseReference postRef = databaseHelper
            .getDatabaseReference()
            .child(DatabaseHelper.POSTS_DB_KEY + "/" + postId + "/commentsCount");
    postRef.runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            Integer currentValue = mutableData.getValue(Integer.class);
            if (currentValue != null && currentValue >= 1) {
                mutableData.setValue(currentValue - 1);
            }

            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
            LogUtil.logInfo(TAG, "Updating comments count transaction is completed.");
            if (onTaskCompleteListener != null) {
                onTaskCompleteListener.onTaskComplete(true);
            }
        }
    });
}
 
Example #8
Source File: PostInteractor.java    From social-app-android with Apache License 2.0 6 votes vote down vote up
public void incrementWatchersCount(String postId) {
    DatabaseReference postRef = databaseHelper.getDatabaseReference().child(DatabaseHelper.POSTS_DB_KEY + "/" + postId + "/watchersCount");
    postRef.runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            Integer currentValue = mutableData.getValue(Integer.class);
            if (currentValue == null) {
                mutableData.setValue(1);
            } else {
                mutableData.setValue(currentValue + 1);
            }

            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
            LogUtil.logInfo(TAG, "Updating Watchers count transaction is completed.");
        }
    });
}
 
Example #9
Source File: ProfileInteractor.java    From social-app-android with Apache License 2.0 6 votes vote down vote up
public void updateProfileLikeCountAfterRemovingPost(Post post) {
    DatabaseReference profileRef = databaseHelper
            .getDatabaseReference()
            .child(DatabaseHelper.PROFILES_DB_KEY + "/" + post.getAuthorId() + "/likesCount");
    final long likesByPostCount = post.getLikesCount();

    profileRef.runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            Integer currentValue = mutableData.getValue(Integer.class);
            if (currentValue != null && currentValue >= likesByPostCount) {
                mutableData.setValue(currentValue - likesByPostCount);
            }

            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
            LogUtil.logInfo(TAG, "Updating likes count transaction is completed.");
        }
    });

}
 
Example #10
Source File: RxDatabaseReference.java    From rxfirebase with Apache License 2.0 5 votes vote down vote up
/**
 * @param emitter
 * @param function
 * @return
 */
@NonNull
@CheckReturnValue
public static Transaction.Handler transaction(
        @NonNull final SingleEmitter<DataSnapshot> emitter,
        @NonNull final Function<MutableData, Transaction.Result> function) {
    return new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            try {
                return function.apply(mutableData);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public void onComplete(@Nullable DatabaseError databaseError,
                               boolean committed,
                               @NonNull DataSnapshot dataSnapshot) {
            if (!emitter.isDisposed()) {
                if (null == databaseError) {
                    emitter.onSuccess(dataSnapshot);
                } else {
                    emitter.onError(databaseError.toException());
                }
            }
        }
    };
}
 
Example #11
Source File: RxDatabaseReference.java    From rxfirebase with Apache License 2.0 5 votes vote down vote up
/**
 * @param ref
 * @param function
 * @param fireLocalEvents
 * @return
 */
@NonNull
@CheckReturnValue
public static Single<DataSnapshot> transaction(
        @NonNull final DatabaseReference ref,
        @NonNull final Function<MutableData, Transaction.Result> function,
        final boolean fireLocalEvents) {
    return Single.create(new SingleOnSubscribe<DataSnapshot>() {
        @Override
        public void subscribe(
                @NonNull final SingleEmitter<DataSnapshot> emit) throws Exception {
            ref.runTransaction(transaction(emit, function), fireLocalEvents);
        }
    });
}
 
Example #12
Source File: RxDatabaseReference.java    From rxfirebase with Apache License 2.0 5 votes vote down vote up
/**
 * @param ref
 * @param function
 * @return
 */
@NonNull
@CheckReturnValue
public static Single<DataSnapshot> transaction(
        @NonNull final DatabaseReference ref,
        @NonNull final Function<MutableData, Transaction.Result> function) {
    return Single.create(new SingleOnSubscribe<DataSnapshot>() {
        @Override
        public void subscribe(
                @NonNull final SingleEmitter<DataSnapshot> emit) throws Exception {
            ref.runTransaction(transaction(emit, function));
        }
    });
}
 
Example #13
Source File: RxFirebaseDatabase.java    From rxfirebase with Apache License 2.0 5 votes vote down vote up
/**
 * @param ref
 * @param fireLocalEvents
 * @param function
 * @return
 * ref.runTransaction(handler, fireLocalEvents);
 */
@NonNull
@CheckReturnValue
public static Single<DataSnapshot> runTransaction(
        @NonNull final DatabaseReference ref,
        @NonNull final Function<MutableData, Transaction.Result> function,
        final boolean fireLocalEvents) {
    return RxValue.transaction(ref, function, fireLocalEvents);
}
 
Example #14
Source File: RxFirebaseDatabase.java    From rxfirebase with Apache License 2.0 5 votes vote down vote up
/**
 * @param ref
 * @param function
 * @return
 */
@NonNull
@CheckReturnValue
public static Single<DataSnapshot> runTransaction(
        @NonNull final DatabaseReference ref,
        @NonNull final Function<MutableData, Transaction.Result> function) {
    return RxValue.transaction(ref, function);
}
 
Example #15
Source File: RxValue.java    From rxfirebase with Apache License 2.0 5 votes vote down vote up
/**
 * @param emitter
 * @param function
 * @return
 */
@NonNull
@CheckReturnValue
public static Transaction.Handler transaction(
        @NonNull final SingleEmitter<DataSnapshot> emitter,
        @NonNull final Function<MutableData, Transaction.Result> function) {
    return new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            try {
                return function.apply(mutableData);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public void onComplete(@Nullable DatabaseError databaseError,
                               boolean committed,
                               @NonNull DataSnapshot dataSnapshot) {
            if (!emitter.isDisposed()) {
                if (null == databaseError) {
                    emitter.onSuccess(dataSnapshot);
                } else {
                    emitter.onError(databaseError.toException());
                }
            }
        }
    };
}
 
Example #16
Source File: RxValue.java    From rxfirebase with Apache License 2.0 5 votes vote down vote up
/**
 * @param ref
 * @param function
 * @param fireLocalEvents
 * @return
 */
@NonNull
@CheckReturnValue
public static Single<DataSnapshot> transaction(
        @NonNull final DatabaseReference ref,
        @NonNull final Function<MutableData, Transaction.Result> function,
        final boolean fireLocalEvents) {
    return Single.create(new SingleOnSubscribe<DataSnapshot>() {
        @Override
        public void subscribe(
                @NonNull final SingleEmitter<DataSnapshot> emit) throws Exception {
            ref.runTransaction(transaction(emit, function), fireLocalEvents);
        }
    });
}
 
Example #17
Source File: RxValue.java    From rxfirebase with Apache License 2.0 5 votes vote down vote up
/**
 * @param ref
 * @param function
 * @return
 */
@NonNull
@CheckReturnValue
public static Single<DataSnapshot> transaction(
        @NonNull final DatabaseReference ref,
        @NonNull final Function<MutableData, Transaction.Result> function) {
    return Single.create(new SingleOnSubscribe<DataSnapshot>() {
        @Override
        public void subscribe(
                @NonNull final SingleEmitter<DataSnapshot> emit) throws Exception {
            ref.runTransaction(transaction(emit, function));
        }
    });
}
 
Example #18
Source File: RepoDatabase.java    From TvAppRepo with Apache License 2.0 5 votes vote down vote up
public void incrementApkViews(Apk app) {
    databaseReference.child(app.getKey()).child("views").runTransaction(
            new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            Long updatedViews = mutableData.getValue(Long.class) + 1;
            mutableData.setValue(updatedViews);
            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
        }
    });
}
 
Example #19
Source File: RepoDatabase.java    From TvAppRepo with Apache License 2.0 5 votes vote down vote up
public void incrementApkDownloads(Apk app) {
    databaseReference.child(app.getKey()).child("downloads").runTransaction(
            new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            Long updatedViews = mutableData.getValue(Long.class) + 1;
            mutableData.setValue(updatedViews);
            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
        }
    });
}
 
Example #20
Source File: PostListFragment.java    From quickstart-android with Apache License 2.0 5 votes vote down vote up
private void onStarClicked(DatabaseReference postRef) {
    postRef.runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            Post p = mutableData.getValue(Post.class);
            if (p == null) {
                return Transaction.success(mutableData);
            }

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

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

        @Override
        public void onComplete(DatabaseError databaseError, boolean committed,
                               DataSnapshot currentData) {
            // Transaction completed
            Log.d(TAG, "postTransaction:onComplete:" + databaseError);
        }
    });
}
 
Example #21
Source File: ClusterMapContributeEditActivity.java    From intra42 with Apache License 2.0 5 votes vote down vote up
void save() {
    app.firebaseRefClusterMapContribute.child(clusterSlug).runTransaction(new Transaction.Handler() {
        @NonNull
        @Override
        public Transaction.Result doTransaction(@NonNull MutableData mutableData) {
            Cluster clusterMutable = mutableData.getValue(Cluster.class);
            if (clusterMutable == null) {
                return Transaction.success(mutableData);
            }

            clusterMutable.width = cluster.width;
            clusterMutable.height = cluster.height;
            clusterMutable.map = cluster.map;

            Map<String, Object> export = clusterMutable.toMap();
            mutableData.setValue(export);
            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b,
                               DataSnapshot dataSnapshot) {
            // Transaction completed
            if (databaseError != null)
                FirebaseCrashlytics.getInstance().log("postTransaction:onComplete:" + databaseError);
        }
    });
}
 
Example #22
Source File: TransactionHandlerTest.java    From gdx-fireapp with Apache License 2.0 5 votes vote down vote up
@Override
public void setup() throws Exception {
    super.setup();
    PowerMockito.mockStatic(MutableData.class);
    PowerMockito.mockStatic(Transaction.class);
    PowerMockito.mockStatic(GdxFIRLogger.class);
}
 
Example #23
Source File: ChatActivity.java    From FChat with MIT License 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_chat);
    parent_view = findViewById(android.R.id.content);
    pfbd = new ParseFirebaseData(this);
    set = new SettingsAPI(this);

    // animation transition
    ViewCompat.setTransitionName(parent_view, KEY_FRIEND);

    // initialize conversation data
    Intent intent = getIntent();
    friend = (Friend) intent.getExtras().getSerializable(KEY_FRIEND);
    initToolbar();

    iniComponen();
    chatNode_1 = set.readSetting(Constants.PREF_MY_ID) + "-" + friend.getId();
    chatNode_2 = friend.getId() + "-" + set.readSetting(Constants.PREF_MY_ID);

    valueEventListener=new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Log.d(Constants.LOG_TAG,"Data changed from activity");
            if (dataSnapshot.hasChild(chatNode_1)) {
                chatNode = chatNode_1;
            } else if (dataSnapshot.hasChild(chatNode_2)) {
                chatNode = chatNode_2;
            } else {
                chatNode = chatNode_1;
            }
            items.clear();
            items.addAll(pfbd.getMessagesForSingleUser(dataSnapshot.child(chatNode)));

            //Here we are traversing all the messages and mark all received messages read

            for (DataSnapshot data : dataSnapshot.child(chatNode).getChildren()) {
                if (data.child(Constants.NODE_RECEIVER_ID).getValue().toString().equals(set.readSetting(Constants.PREF_MY_ID))) {
                    data.child(Constants.NODE_IS_READ).getRef().runTransaction(new Transaction.Handler() {
                        @NonNull
                        @Override
                        public Transaction.Result doTransaction(@NonNull MutableData mutableData) {
                            mutableData.setValue(true);
                            return Transaction.success(mutableData);
                        }

                        @Override
                        public void onComplete(@Nullable DatabaseError databaseError, boolean b, @Nullable DataSnapshot dataSnapshot) {

                        }
                    });
                }
            }

            // TODO: 12/09/18 Change it to recyclerview
            mAdapter = new ChatDetailsListAdapter(ChatActivity.this, items);
            listview.setAdapter(mAdapter);
            listview.requestFocus();
            registerForContextMenu(listview);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            new CustomToast(ChatActivity.this).showError(getString(R.string.error_could_not_connect));
        }
    };

    ref = FirebaseDatabase.getInstance().getReference(Constants.MESSAGE_CHILD);
    ref.addValueEventListener(valueEventListener);

    // for system bar in lollipop
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        Tools.systemBarLolipop(this);
    }
}