[英]How to delete selected child on Firebase Database Android
我试图通过将唯一键设置为null从数据库中删除一个子级。 我要做的是-按住列表项以获取“警报对话框”,然后按删除我选择的条目。 问题是当我检索密钥时,它会返回我所有的密钥。 到目前为止,我设法做到的最接近的就是从数据库中删除所有内容。 请在下面检查我的代码快照:
mLocationListView.setLongClickable(true);
mLocationListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this)
.setTitle("Delete a Location")
.setMessage("Do you want to delete your location?")
.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//Problem is here. if I exclude .child(pushKey)everything is deleted from the database.
DatabaseReference db_node = FirebaseDatabase.getInstance().getReference().getRoot().child("locations").child(pushKey);
db_node.setValue(null);
}
});
AlertDialog alert = builder.create();
alert.show();
return true;
}
});
这是我检索pushKey的方法。 有什么建议如何以更适当的方式做到这一点? (如果有)
queryRef.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
locationCurrent = dataSnapshot.getValue(LocationCurrent.class);
mLocationAdapter.add(locationCurrent);
pushKey = dataSnapshot.getKey();
Log.i("PUSH KEY ", pushKey);
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
locationCurrent = dataSnapshot.getValue(LocationCurrent.class);
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
我当时也在考虑将Key放入数据库,但没有意义,必须有最有效的解决方案。
更新:
我尝试使用将单个值事件侦听器附加到查询的另一种方法来执行此操作,但是由于无法确定单击哪个列表项,因此删除了整个数据库,因此该方法不起作用。 基本上,我需要单击一个列表项并将其删除。 但这行不通。 我完全按照下面的链接进行操作:
有什么建议么?
在LocationCurrent.class中添加一个称为refKey
的瞬态变量。 将引用保存在onChildAdded
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
locationCurrent = dataSnapshot.getValue(LocationCurrent.class);
locationCurrent.setRefKey(dataSnapshot.getKey());
mLocationAdapter.add(locationCurrent);
}
在删除时,请执行以下操作:
mLocationListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
DatabaseReference db_node = FirebaseDatabase.getInstance().getReference().child("locations").child(mLocationAdapter.getItem(position).getRefKey());
db_node.removeValue();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.