2016-09-19 34 views
0

迄今爲止我嘗試過的所有方法只返回父母鍵而不是自動生成的按鍵。我希望每當我推送數據時從firebase中自動生成密鑰

String key = rootref.child("user").push().getKey(); 
newUser.setUid(key); 
Log.i("#####",key); 
Map<String, Object> childUpdates = new HashMap<>(); 
childUpdates.put(key,newUser); 
rootref.updateChildren(childUpdates); 

這裏getkey()將返回「用戶」給我,而我想自動生成key.Prior這個我一直在使用一個子事件偵聽器和listenerforsinglevaluedevent但即使是這些給出了相同的output.Any幫助將嘗試不勝感激!

+0

調用'push()。getKey()'將返回一個新的推送ID。如果您在閱讀過程中遇到推送ID的問題,請添加讀取您的問題的代碼。 –

+0

這就是問題......我沒有得到新的推送ID ...我得到的是用戶的父母ID ...我不明白你的意思,只要我添加安對象與推我想推id生成,並且這就是我的代碼 –

+0

我剛剛跑'String key = rootref.child(「user」)。push()。getKey(); System.out.println(key);'並打印'-KS4eeDhFqKcKO3oBy6-'。 –

回答

0

我正在檢查你的代碼並沒有看到setValue。這就是getKey返回「user」的原因。它應該像 rootref.child("user").push().setValue(UserObject)

試試這個! 我使用這段代碼。

rootref.push().setValue(UserObject).addOnCompleteListener(new OnCompleteListener<Void>() { 
     @Override 
     public void onComplete(@NonNull Task<Void> task) { 
      if (task.isSuccessful()) { 
       Toast.makeText(getApplicationContext(),rootref.push().getKey(),Toast.LENGT_LONG).show(); 
      } 
     } 
    }); 
相關問題