在Firebase中自动增加一个值 [英] Auto-increment a value in Firebase

查看:215
本文介绍了在Firebase中自动增加一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从Android客户端自动增加存储在Firebase中的值?目前:我声明 int id = 1 。当我增加,我看到值2,3等被存储。这很好,但是当我重新运行这个项目的时候, id 被设置为等于1。



它的行为像一个静态变量,所以我可以创建一个ID从1到无穷大而不需要重新设置。


$ b

UPDATED FAILED



我使用以下方法将Firebase引用和字符串传递给函数incrementCounter。

  if(language_chosen.equalsIgnoreCase(english))
{
Firebase publRef = f.child ( 语言)子( 英语)子( 信息)。;
Firebase newPublRef = publRef.push();
writeMsgActivity demo = new writeMsgActivity();
demo.incrementCounter(newPublRef,the_msg_enter);





$ b现在我尝试在 public void incrementCounter(Firebase publref,String my_msg)
在oncomplete方法,但它给了我一个错误。

 <$ c (){$ c $> public void incrementCounter(Firebase publref,String my_msg){
publref.runTransaction(new Transaction.Handler(){
@Override
public Transaction.Result doTransaction(final MutableData currentData){ $())
if(currentData.getValue()== null){
currentData.setValue(1);
} else {
currentData.setValue((Long)currentData.getValue + 1);
}

return Transaction.success(currentData);
}
$ b $ public void onComplete(FirebaseError firebaseError,boolean committed,DataSnapshot currentData ){
if(firebaseError!= null){
System.out.println(Firebase计数器增量失败);
} else {
System.out.println(Firebase counter incremented。);

Map< String,Object> publ = new HashMap< String,Object>();
publ.put(pubMsg,my_msg);
publ.put(id,currentData);
publref.setValue(publ);
}
}
});




$ b

更新已解决

 最终Firebase upvoteref = new Firebase(https://shareurday.firebaseio.com/Message/+ msg_id +/ upvotes); 

upvoteref.runTransaction(new Transaction.Handler(){
@Override
public Transaction.Result doTransaction(final MutableData currentData){
if(currentData.getValue )== null){
currentData.setValue(1);
} else {
currentData.setValue((Long)currentData.getValue()+ 1);
}
return Transaction.success(currentData);
}

public void onComplete(firebaseError firebaseError,boolean committed,DataSnapshot currentData){
if(firebaseError!= null){
System.out.println(Firebase计数器增量失败。);
} else {
System.out.println(Firebase counter increment。);
}
}
});

变量msg_id是来自push的随机生成的id。

下面是一个递增单个计数器的示例方法。关键的想法是,您要么创建条目(将其设置为1),要么对现有条目进行变异。在这里使用事务可以确保如果多个客户端同时尝试增加计数器,所有请求最终都会成功。从Firebase文档(重点是我的):


使用我们的事务功能处理可能被并发更新损坏的复杂数据



  public void incrementCounter(){
firebase.runTransaction new Transaction.Handler(){
@Override
public Transaction.Result doTransaction(final MutableData currentData){
if(currentData.getValue()== null){
currentData。 setValue(1);
} else {
currentData.setValue((Long)currentData.getValue()+ 1);
}

return Transaction.success currentData);
}

@Override
public void onComplete(firebaseError firebaseError,boolean committed,DataSnapshot currentData){$ b $ if(firebaseError!= null){
Log.d(Firebase counter increm ent失败了。);
} else {
Log.d(Firebase counter incremented。);
}
}
});
}


How do I auto increment a value stored in Firebase from an Android client?

Currently: I declare int id = 1. When I increment, I see the values 2, 3 etc. being stored. That's fine, but when I re-run the project, id is set equal to 1 again.

I want it to behave like a static variable, so I can create an id which will go from 1 to infinity without resetting.

UPDATED FAILED

I used the following to pass the Firebase reference and a string to the function incrementCounter.

if(language_chosen.equalsIgnoreCase("english"))
 {
   Firebase publRef = f.child("Language").child("English").child("Message");
   Firebase newPublRef = publRef.push();
   writeMsgActivity demo = new writeMsgActivity();
   demo.incrementCounter(newPublRef,the_msg_enter);                                 
  }

Now I try to use the passed reference and string at public void incrementCounter(Firebase publref,String my_msg) in the oncomplete method but it gives me an error.

   public void incrementCounter(Firebase publref,String my_msg) {
    publref.runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(final MutableData currentData) {
            if (currentData.getValue() == null) {
                currentData.setValue(1);
            } else {
                currentData.setValue((Long) currentData.getValue() + 1);
            }

            return Transaction.success(currentData);
        }

        public void onComplete(FirebaseError firebaseError, boolean committed, DataSnapshot currentData) {
            if (firebaseError != null) {
                System.out.println("Firebase counter increment failed.");
            } else {
                System.out.println("Firebase counter increment succeeded.");

                Map<String, Object> publ = new HashMap<String, Object>();
                publ.put("pubMsg", my_msg);
                publ.put("id",currentData);
                publref.setValue(publ);
            }
        }
    });
}

UPDATED SOLVED

                final Firebase upvoteref = new Firebase("https://shareurday.firebaseio.com/Message/"+msg_id+"/upvotes"); 

            upvoteref.runTransaction(new Transaction.Handler() {
                @Override
                public Transaction.Result doTransaction(final MutableData currentData) {
                    if (currentData.getValue() == null) {
                        currentData.setValue(1);
                    } else {
                        currentData.setValue((Long) currentData.getValue() + 1);
                    }
                    return Transaction.success(currentData);
                }

                public void onComplete(FirebaseError firebaseError, boolean committed, DataSnapshot currentData) {
                    if (firebaseError != null) {
                        System.out.println("Firebase counter increment failed.");
                    } else {
                        System.out.println("Firebase counter increment succeeded.");
                    }
                }
            });

The variable msg_id is the random generated id from push.

解决方案

Here's an example method that increments a single counter. The key idea is that you are either creating the entry (setting it equal to 1) or mutating the existing entry. Using a transaction here ensures that if multiple clients attempt to increment the counter at the same time, all requests will eventually succeed. From the Firebase documentation (emphasis mine):

Use our transactions feature when working with complex data that could be corrupted by concurrent updates

public void incrementCounter() {
    firebase.runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(final MutableData currentData) {
            if (currentData.getValue() == null) {
                currentData.setValue(1);
            } else {
                currentData.setValue((Long) currentData.getValue() + 1);
            }

            return Transaction.success(currentData);
        }

        @Override
        public void onComplete(FirebaseError firebaseError, boolean committed, DataSnapshot currentData) {
            if (firebaseError != null) {
                Log.d("Firebase counter increment failed.");
            } else {
                Log.d("Firebase counter increment succeeded.");
            }
        }
    });
}

这篇关于在Firebase中自动增加一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆