2016-05-31 83 views
2

這是我在Firebase中添加記錄的代碼。有可變的外部稱爲restauCount價值(int)爲1如何避免覆蓋Firebase中的數據

public void sendMessage(){ 

    int restauCount = 1; 
    String identifier ="Restaurant" + restauCount; 
    Firebase userRef = firebaseRef.child("Caloocan"); 
    EditText nameInput = (EditText) findViewById(R.id.nameTxt); 
    String name = nameInput.getText().toString(); 

    EditText locInput = (EditText) findViewById(R.id.locationTxt); 
    String location = locInput.getText().toString(); 

    EditText typeInput = (EditText) findViewById(R.id.typeTxt); 
    String foodtype = typeInput.getText().toString(); 
    if (!name.equals("")){ 
     Map<String, String> caloocan = new HashMap<String, String>(); 
     caloocan.put("resname", name); 
     caloocan.put("resloc", location); 
     caloocan.put("foodtype", foodtype); 

     Map<String, Map<String, String>> users = new HashMap<String, Map<String, String>>(); 
     users.put(identifier,caloocan); 

     userRef.setValue(users); 
     restauCount++; 
    } 
} 

當我再次運行sendessage()。我將輸入字段,當我點擊ADD時,它將被添加到FireBase中,但是當我添加新數據時。它覆蓋了舊數據輸入?如何在不覆蓋數據的情況下在火災中添加多個數據? restauCount是爲了增加我輸入的餐廳數量,

回答

0

你需要更新identifier它保持不變:

int restauCount = 1; 
String identifier ="Restaurant" + restauCount; 

嘗試類似於:

long restauCount = System.currentTimeMillis(); 
    String identifier ="Restaurant" + restauCount; 

這裏每次發送sendMessage()您的標識有一個特定的id作爲以毫秒爲單位的當前時間的時間+「餐廳」

如果重要的是保持INT數字讓我知道

+0

我的代碼的錯誤是在.put()不在我的櫃檯restau,對不起 –

+0

你試過我的答案嗎?,因爲爲了避免覆蓋你需要的數據每次一個新的標識符 –

+0

它的工作原理,但我需要一個唯一的ID來輕鬆檢索數據,如果我將使用它。任何想法?當我按下按鈕時會增加計數器嗎? –

1

使用

userRef.setValue(users).push(); 

,而不是userRef.setValue(users);

+0

有一個錯誤用推唯一密鑰每次。我的應用程序關閉時,我試着把這個「userRef.setValue(userRef.push());」 –

+0

它不是userRef.setValue(userRef.push()); 它是userRef.setValue(users).push(); –

+0

錯誤:無法解析方法'push()' –

0

您使用的始終所述相同REF

String identifier ="Restaurant" + restauCount; 
Firebase userRef = firebaseRef.child("Caloocan"); 
userRef.setValue(users); 
restauCount++; 

Check the doc

以這種方式使用setValue()將覆蓋指定位置的數據,包括任何子節點。

在你的情況下,你的正在覆蓋相同的數據出於這個原因。

您應該使用push()方法在每次將新的子項添加到指定的Firebase引用時生成一個唯一的ID。

Firebase userRef = firebaseRef.child("Caloocan"); 
Firebase newRef = userRef.push(); 
newRef.setValue(users); 

//to get the key 
String key = newRef.getKey(); 
1

userRef.push().setValue(users); 推送()方法產生一個新的子被添加到指定的火力地堡參考