how do i auto increment a value in firebase

南笙酒味 提交于 2019-12-08 17:01:23

I think you might want to look at Transaction. If reference is your FirebaseReference pointing to the number to be incremented, you can do something like this:

reference.runTransaction(new Transaction.Handler() {
    @Override
    public Transaction.Result doTransaction(MutableData mutableData) {
        if (mutableData.getValue() == null) {
            mutableData.setValue(1);
        } else {
            int count = mutableData.getValue(Integer.class);
            mutableData.setValue(count + 1);
        }
        return Transaction.success(mutableData);
    }

    @Override
    public void onComplete(DatabaseError databaseError, boolean success, DataSnapshot dataSnapshot) {
        // Analyse databaseError for any error during increment
    }
});

Note that two Transactions can't be executed at the same time, so you are sure that the count is updated properly. You can have more details here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!