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
中显示来自firebase的每个元素。长按一下,我想删除所选项目。我可以从前端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 :(得分:2)
如果我理解你的话,你的数据集就像这样(在你的Firebase仪表板中):
yourApp:
food -
FiReBaSeGenErAtEdKeY - // Mapped to object Food
- name: "food"
- color: "color"
MoReGenErAtEdKeYs2 +
MoReGenErAtEdKeYs3 +
MoReGenErAtEdKeYs4 +
您可以仅使用键删除值,更具体地说,是创建&#34;路径&#34;的所有键。对象。例如,如果要删除Food对象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);
参考文献: