2016-03-21 30 views
2

firebase的Java API似乎不太清楚。我對象添加到我的火力點,如:通過索引或類刪除firebase元素

Food foodObj=new Food(); 
foodObj.setValue("name",food);//food is a string 
foodObj.setValue("color",color); 
myFirebaseRef.push().setValue(foodObj.getKeysValues()); 

我顯示了在listView從火力點每一個元素。長按一下,我想刪除選定的項目。我可以從前端獲得索引和對象arrayList

listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { 
    @Override 
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { 

     final int temp = position; 
     new AlertDialog.Builder(FridgeActivity.this) 
       .setMessage("Do you want to delete this item?") 
       .setPositiveButton("Yes", new DialogInterface.OnClickListener() { 
        @Override 
        public void onClick(DialogInterface dialog, int which) { 
         Log.d(tag, "should delete:" + Integer.toString(temp)); 
         Food mess = fridge.get(temp); 

        } 
       }) 
      .setNegativeButton("No", null) 
      .show(); 
     return true; 
    } 
}); 

我還沒弄清楚如何刪除mess。我試過myFirebaseRef.removeVal(),但是它會從數據庫中刪除所有內容。

+0

getKeysValues()返回什麼?您不需要將地圖保存到Firebase,您可以保存一個Bean對象。 –

+0

你需要獲得一個FirebaseRef到你想要刪除的特定元素,然後使用removeValue() –

+0

@RonHarlev我如何獲得一個特定的元素?一些元素具有相同的名稱。 – depperm

回答

2

如果我理解你的權利,你的數據集看起來像這樣(在你的火力地堡儀表板):

yourApp: 
    food - 
     FiReBaSeGenErAtEdKeY - // Mapped to object Food 
           - name: "food" 
           - color: "color" 
     MoReGenErAtEdKeYs2  + 
     MoReGenErAtEdKeYs3  + 
     MoReGenErAtEdKeYs4  + 

可以只能通過使用密鑰,更具體地說,所有鍵刪除值創造對象的「路徑」。例如,如果您想刪除食品對象FiReBaSeGenErAtEdKeY,則需要知道其路徑。在這種情況下,您的路徑將爲<your_ref>/food/FiReBaSeGenErAtEdKeY。要做到這一點:

myFirebaseRef 
    .child("food") //the food branch 
    .child("FiReBaSeGenErAtEdKeY") // the key of the object 
    .removeValue(); // delete 

或者,如果你想刪除color價值,你的道路將<your_ref>/food/FiReBaSeGenErAtEdKeY/color

myFirebaseRef 
     .child("food") //the food branch 
     .child("FiReBaSeGenErAtEdKeY") // the key of the object 
     .child("color") //actually using "color" because that is the name of the key. This will remove the value, and because there are no more values, the key is empty, therefore it will be deleted too. 
     .removeValue(); // delete 

可能很難拿到鑰匙後 - 事實。有辦法從DataSnapshot得到它,但我喜歡設置我的對象是這樣的:

public class Food { 
    private String key;  // add the key here 
    private String name; 
    private String color; 
    //other fields 

    public Food(){ /* empty constructor needed by Firebase */ } 

    //Add all of your accessors 

} 

然後,當你想創建/保存的食物對象:

String key = myFireBaseRef.push().getKey(); 
Food food = new Food(); 
food.setKey(key); 
food.setColor(color); 
food.setName(name); 

//Then to save the object: 
myFirebaseRef 
    .child("food") //move to the "food" branch 
    .child(food.getKey()) 
    .setValue(food); 

參考文獻: