2016-05-31 80 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); 推送()方法产生一个新的子被添加到指定的火力地堡参考