Firebase Android delete node key in ListView on longpress

假装没事ソ 提交于 2019-12-23 19:44:46

问题


Tried to search a lot but after 2 days I'm still stucked on this problem. I have the following database in my Firebase which is populated in my ListView. For each row in the ListView is displayed data1 and data2.

 test-3db7e
  |
  +---users
       |
       +---W9KkXAidmHgyOpyeQPeT5YxgQI42
            |
            +---data
            |    |
            |    +----LIv-OeQdixT0q6NZ-jL
            |    |     |
            |    |     +---data1: "Data1"
            |    |     |
            |    |     +---data2: "Data2"
            |    |
            |    +----LIv-R3PRKaEHaAcMjWu
            |          |
            |          +---data1: "Data1"
            |          |
            |          +---data2: "Data2"
            |
            +---name: "The user's name"

Until now it all seams ok, I can upload data from my app and the listview syncs perfectly with the Firebase console.

I made the ListView using the folling code:

    //Updating the listview
    databaseReference.child("users").child(user).child("data").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            //Getting all the children at this level
            Iterable<DataSnapshot> children = dataSnapshot.getChildren();
            dataArrayAdapter.clear();

            for (DataSnapshot child : children) {

                Data data = child.getValue(Data.class);
                dataList.add(data);
                dataArrayAdapter.notifyDataSetChanged();

            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

Also I created the Data.class to store the values from the previous code to the listview.

    package com.mypackge.firebase;

    public class Data {

        private String data1;
        private String data2;

        public String getData1() {
            return data1;
        }

        public void setData1(String data1) {
            this.data1 = data1;
        }

        public String getData2() {
            return data2;
        }

        public void setData2(String data2) {
            this.data2 = data2;
        }

        public String toString() {
            return data1 +"\n"+data2;
        }
    }

The problem now is with the following code, on long press on the list view I want to remove (if pressed yes on the dialog) the row that was pressed.

     /**
     *
     * Deleting data on long press
     *
     */

    //Creating a dialog interface
    final DialogInterface.OnClickListener dialogClickListner = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {

            if(i==DialogInterface.BUTTON_POSITIVE){

            //    WHAT TO DO HERE?????

            }else if(i== DialogInterface.BUTTON_NEGATIVE){


            }

        }
    };

    //Creating the Item on Click Listner
    lstViewData.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long l) {
            //Creating the alert dialog
            AlertDialog.Builder builder = new AlertDialog.Builder(adapterView.getContext());
            builder.setMessage("Do you want to delete?")
                    .setPositiveButton("Yes", dialogClickListner)
                    .setNegativeButton("No",dialogClickListner).show();

            //    WHAT TO DO HERE?????

            return false;
        }
    });

Thank you all for your time!!!


回答1:


The key for solving this problem is to add the pushed key that is generated when you are creating an object of Data class to the database. So beside data1 and data2 fields, add another field named key (also of type String). Please also add the corresponding setter and getter for this new field.

Now, this is how you need actually to create on object:

DatabaseReference dataRef = databaseReference.child("users").child(user).child("data");
String key = dataRef.push().getKey();
Data data = new Data();
data.setData1("data1");
data.setData2("data2");
data.setKey(key);
dataRef.child(key).setValue(data);

Now your Data object has the key field populated with the actual key from the database. To display the data and to remove a particular object that was clicked, please use the following code:

ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        ArrayList<Data> list = new ArrayList<>();
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            Data data = ds.getValue(Data.class);
            list.add(data);
        }
        ListView listView = (ListView) findViewById(R.id.list_view);
        ArrayAdapter<Data> arrayAdapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, list);
        listView.setAdapter(arrayAdapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
                builder.setMessage("Do you want to delete?");

                builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int i) {
                        String key = arrayAdapter.getItem(i).getKey();
                        dataRef.child(key).removeValue();
                    }
                });

                builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int i) {
                        dialog.dismiss();
                    }
                });

                AlertDialog dialog = builder.create();
                dialog.show();
            }
        });
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {}
};
dataRef.addListenerForSingleValueEvent(valueEventListener);


来源:https://stackoverflow.com/questions/51656064/firebase-android-delete-node-key-in-listview-on-longpress

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!