在 Firebase 中自动递增值
2022-09-04 01:31:44
如何从 Android 客户端自动递增存储在 Firebase 中的值?
目前:我声明.当我递增时,我看到值2,3等被存储。这很好,但是当我重新运行项目时,再次设置为等于1。int id = 1
id
我希望它的行为像一个静态变量,所以我可以创建一个id,它将从1变为无穷大,而无需重置。
更新失败
我使用以下内容将Firebase引用和字符串传递给函数增量计数器。
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);
}
现在我尝试在 oncomplete 方法中使用传递的引用和字符串 at,但它给了我一个错误。public void incrementCounter(Firebase publref,String my_msg)
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);
}
}
});
}
已更新已解决
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.");
}
}
});
变量 msg_id是从推送中随机生成的 id。