2016-02-26 71 views
1
-uniqueid1 
     status:0 
     userTokenId: uniqueid(which is null) 

我遇到了种族问题,我不知道firebase是如何实施这种情况的。该问题如下:围绕特定情况下的火情况竞赛火力堡

  1. 用户检查状态为状态是否为0。
  2. 如果状态为0它增加了它的令牌来userTokenid字段和状态1
  3. 如果不是那么它一点儿也不添加它的tokenid。

现在的问题是,当2个或更多的用户检查状态0和两个输入2点。这个问题可能毫无意义,但我需要确认。我必须担心这种情况吗?

firebase.child('uniqueid1'); 

firebase.addListenerForSingleValueEvent(new ValueEventListener() { 
    @Override 
    public void onDataChange(DataSnapshot dataSnapshot) { 
     if(datasnapshot.child('status').getValue().equals(0)){ 
      //update record for userTokenId and status 
     } 
     else{ 
      //don't update 
     } 
    } 

    @Override 
    public void onCancelled(FirebaseError firebaseError) { 
    } 
}); 

回答

3

如果这两个客户端发生了setValue()updateChildren()呼叫,最后写胜更新大约在同一时间相同的值。

如果你不想那样,你应该可以是using a transaction。从文档:

在处理复杂数据,可以通过并发修改,如增量计数器被破坏工作,我们提供了一个transaction operation。您给这个操作两个参数:一个更新函数和一个可选的完成回调。更新函数将数据的当前状态作为参数,并将返回您想要编写的新的期望状态。例如,如果我们想要增加在一个特定的博客文章upvotes的数量,我们会写一个交易如下​​所示:

Firebase upvotesRef = new Firebase("https://docs-examples.firebaseio.com/android/saving-data/fireblog/posts/-JRHTHaIs-jNPLXOQivY/upvotes"); 
upvotesRef.runTransaction(new Transaction.Handler() { 
    @Override 
    public Transaction.Result doTransaction(MutableData currentData) { 
     if(currentData.getValue() == null) { 
      currentData.setValue(1); 
     } else { 
      currentData.setValue((Long) currentData.getValue() + 1); 
     } 
     return Transaction.success(currentData); //we can also abort by calling Transaction.abort() 
    } 
    @Override 
    public void onComplete(FirebaseError firebaseError, boolean committed, DataSnapshot currentData) { 
     //This method will be called once with the results of the transaction. 
    } 
}); 

阅读documentation on transaction()的全部细节。

+0

谢谢,你让我的一天.. :) –

+1

在这种情况下,我强烈建议你阅读[适用于Android的Firebase编程指南](https://www.firebase.com/docs/android/guide/)因为这是我从中复制的。在那里度过的一个小时,将防止许多错误和问题。 –

+0

,请检查我的答案..提前致谢 –

0
Firebase ref=firebase.child("order_details/"+orderId); 
      ref.runTransaction(new Transaction.Handler() { 
       @Override 
       public Transaction.Result doTransaction(MutableData currentData) { 
        Log.d("status",currentData.getValue()); 
        int status= (int) currentData.child("status").getValue(); 
        if(status==0){ 
         HashMap<String,Object> map=new HashMap<String, Object>(); 
         map.put("TokenId",sharedPreferences.getString("tokenId","")); 
         map.put("status",1); 
         currentData.setValue(map); 
        } 
       ((MapLoadingActivity)getActivity()).setProgressVisibility(false); 
        return Transaction.success(currentData); 
       } 


       @Override 
       public void onComplete(FirebaseError firebaseError, boolean b, DataSnapshot dataSnapshot) { 

       } 
      }); 

我知道它的后期要问的问题,但doTransaction()是很奇怪的,有时它有时称其只是返回null.Therefore我换我的方法,通过使用PHP的包装class.Please确实表明呼叫火力点到PHP ,如果我的方法是错误的。