我试图通过将唯一键设置为空来从数据库中删除子项。我所做的是 - 按住列表项以获取警报对话框,然后按 删除我选择的条目。问题是当我检索 key 时它会返回所有 key 。到目前为止我最接近的是从数据库中删除所有内容。请检查下面我的代码快照:
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 也放入数据库,但没有意义,必须有最有效的解决方案。
更新:
我尝试使用另一种方法来执行此操作,将单值事件监听器附加到查询,但它不起作用,因为我无法确定单击哪个列表项,因此我删除了整个数据库。基本上,我需要单击列表项并将其删除。但它不起作用。我完全按照下面的链接进行操作:
How to delete from firebase realtime database?
有什么建议吗?
最佳答案
在 LocationCurrent.class 中添加一个名为 refKey
的 transient 变量。将引用保存在 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();
});
关于java - 如何在 Firebase 数据库 Android 上删除选定的子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41313200/