如何在Firebase中增加数字 [英] How to increment number in firebase

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

问题描述

我已经编辑了代码。有用。它增加了火力基地的计数器。但是有一个问题。每当我重新启动应用程序(清除最近的应用程序后),增量重新开始。它不会从以前的数字继续。



公共类MainActivity扩展AppCompatActivity {

 按钮bNext; 
long count;

DatabaseReference mRootRef = FirebaseDatabase.getInstance()。getReference();
DatabaseReference mCounterRef = mRootRef.child(counter);

@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

bNext =(Button)findViewById(R.id.bNext);

bNext.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
mCounterRef.setValue(++ count);
}
});


$ b code
$ b

这是我的数据库

解决方案


  1. count 数字,并将读作 Long 。您不能直接转换为 int 。你可以转换成 long ,或者你可以使用两个转换: int count =(int)(long)...

  2. 您正在使用后增加运算符。它使用该值在之后添加一个
  3. 监听一个改变,否则你将循环,因为 setValue()会导致监听器再次引发火灾,等等。
  4. 正如Frank所指出的那样, Transaction 是安全修改计数器的更好方法。 p $ p> final DatabaseReference mRootRef = FirebaseDatabase.getInstance()。getReference();
    final DatabaseReference mCounterRef = mRootRef.child(counter);
    //监听单个更改
    mCounterRef.addListenerForSingleValueEvent(new ValueEventListener(){
    @Override
    public void onDataChange(DataSnapshot dataSnapshot){
    // getValue()返回Long
    long count =(long)dataSnapshot.child(count)。getValue();

    System.out.println(count before setValue()=+ count) ;

    mCounterRef.child(count).setValue(++ count); //< =更改为++ count

    System.out.println(在setValue()=+ count)之后计数;

    }
    $ b $ @覆盖
    public void onCancelled(DatabaseError databaseError){
    // throw an如果setValue()被拒绝,则返回错误
    throw databaseError.toException();
    }
    });

编辑问题更新:



您可能需要更新安全规则以允许写入权限。添加完成监听器来查看 setValue()是否失败:

  mCounterRef.child(count)。setValue(++ count,new DatabaseReference.CompletionListener(){
@Override $ b $ public void onComplete(DatabaseError databaseError,
DatabaseReference databaseReference){$ b $如果(databaseError!= null){
System.out.println(Error:+ databaseError.getMessage());
}
}
});


I've edited the code. It works. It increment the counter in firebase. But there is 1 problem. Whenever I restart the app (after clear recent app), the increment starts over. It does not continue from previous number.

public class MainActivity extends AppCompatActivity {

Button bNext;
long count;

DatabaseReference mRootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference mCounterRef = mRootRef.child("counter");

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    bNext = (Button) findViewById(R.id.bNext);

    bNext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mCounterRef.setValue(++count);
        }
    });

}
}

this is my database

解决方案

Three things require fixing:

  1. count in your DB is a number and will be read as a Long. You cannot cast directly to int. Instead you can cast to a long, or you could use two casts: int count = (int)(long) ...
  2. You are using the post-increment operator. It adds one after using the value. Use pre-increment instead.
  3. Listen for a single change, otherwise you will loop, because setValue() will cause the listener for fire again, and again, etc.

As Frank notes, a Transaction is the better way to safely modify counters.

    final DatabaseReference mRootRef = FirebaseDatabase.getInstance().getReference();
    final DatabaseReference mCounterRef = mRootRef.child("counter");
    // listen for single change
    mCounterRef.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            // getValue() returns Long
            long count = (long) dataSnapshot.child("count").getValue();

            System.out.println("count before setValue()=" + count);

            mCounterRef.child("count").setValue(++count);  // <= Change to ++count

            System.out.println("count after setValue()=" + count);

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            // throw an error if setValue() is rejected
            throw databaseError.toException();
        }
    });

Update for edited question:

You probably need to update your security rules to allow write access. Add a completion listener to see if setValue() is failing:

mCounterRef.child("count").setValue(++count, new DatabaseReference.CompletionListener() {
    @Override
    public void onComplete(DatabaseError databaseError,
                           DatabaseReference databaseReference) {
        if (databaseError != null) {
            System.out.println("Error: " + databaseError.getMessage());
        }
    }
});

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

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