从Firebase实时数据库中删除Android中的ListView项目

2 人关注

我们有一个问题,当我们使用push()向Firebase实时数据库插入数据时,我们试图从随机生成的密钥中删除数值,但只从应用程序中删除,而不是在实时数据库中,我们无法找出问题所在,请你帮助我们😭。

push() --> in Additem.class

private void StoreProductInformation() {

    Description = InputProductDescription.getText().toString();
    Pname = InputProductName.getText().toString();
    citem obj = new citem(Pname,Description );
    ProductsRef.push().setValue(obj);
    Toast.makeText(Additem.this, "Added To cart", Toast.LENGTH_SHORT).show();
    Intent i =new Intent(this,shoppingcart.class);
    startActivity(i);

removeValue() --> in shoppingcart.class

list.setAdapter(myadapter);
    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> a, View v, int position, long id) {
            AlertDialog.Builder adb=new AlertDialog.Builder(shoppingcart.this);
            adb.setTitle("Delete?");
            adb.setMessage("Are you sure you want to delete " + position);
            final int positionToRemove = position;
            adb.setNegativeButton("Cancel", null);
            adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    mylist.remove(positionToRemove);
                    myadapter.notifyDataSetChanged();
                    //myRef.child("key").removeValue();
            adb.show();

实时数据库

java
android
firebase
firebase-realtime-database
google-cloud-platform
S J
S J
发布于 2022-05-11
1 个回答
Alex Mamo
Alex Mamo
发布于 2022-05-11
已采纳
0 人赞同

你可以解决这个问题的最简单的办法是将推送的ID作为属性存储在每个对象下。

Firebase-root
  --- shoppingcart
        --- -N1kC...ZKwO 👇
        |     |
        |     --- name: "R"
        |     |
        |     --- qty: 3
        |     |
        |     --- key: "-N1kC...ZKwO" 👈
        --- -N1kC...LO3- 👇
              --- name: "Z"
              --- qty: 10
              --- key: "-N1kC...LO3-" 👈

这也意味着持有这两个字段(nameqty)的类现在也应该包含另一个叫做key的字段。因此,假设这个类被称为Item,为了从适配器以及数据库中删除被点击的项目,请使用以下几行代码。

public void onClick(DialogInterface dialog, int which) {
    //Remove the item from the Realtime Database
    Item clickedItem = mylist.get(positionToRemove); 👈
    myRef.child(clickedItem.getKey()).removeValue(); 👈
    //Remove the item from the adapter.
    mylist.remove(positionToRemove);
    myadapter.notifyDataSetChanged();

如果你在你的类中添加了公共的getters,这将会起作用,否则,如果你可以访问公共字段,那么请使用。

myRef.child(clickedItem.key).removeValue();

然而,如果你考虑在某个时间点上尝试使用Cloud Firestore和一个RecyclerView而不是ListView,那么请查看以下你认为更适合你的用例的文章。

  • How to delete a record from Firestore on a RecylerView left/right swipe?
  •