How to remove currently selected item in ListView

2019-09-14 09:20发布

问题:

I am developing an Android app, and I have already implemented authentication with Firebase. After logging in, in my NavigationDrawerActivity I have a ListView that I had set a FirebaseListAdapater to that gets user specific data.

In my onCreate() method I have the following:

        firebaseAuth = FirebaseAuth.getInstance();
        FirebaseUser localUser = firebaseAuth.getCurrentUser();
        String localUserEmail = localUser.getEmail();
        String localUserEmailUniqueID = getEmailAddressUniqueID(localUserEmail);
        String dbUsersRoot = "https://DATABASENAME.firebaseio.com/Users/";
        String dbUniqueRefForCurrentUser = dbUsersRoot + localUserEmailUniqueID +"/parishioners";

        DatabaseReference databaseReferenceCurrentUser = FirebaseDatabase.getInstance().getReferenceFromUrl(dbUniqueRefForCurrentUser);

        final FirebaseListAdapter<String> firebaseListAdapter = new FirebaseListAdapter<String>(
                this,
                String.class,
                android.R.layout.simple_list_item_2,
                databaseReferenceCurrentUser
        ) {
            @Override
            protected void populateView(View v, String model, int position) {
                TextView textView = (TextView) v.findViewById(android.R.id.text1);
                    textView.setText(model);
                }
            };

        mListView.setAdapter(firebaseListAdapter);

Now, in my onStart() method I have added an setOnClickListener to a button that wishes to add a new item into my list , like this :

@Override
    protected void onStart(){
        super.onStart();

        mButtonAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                firebaseAuth = FirebaseAuth.getInstance();
                FirebaseUser localUser = firebaseAuth.getCurrentUser();
                String localUserEmail = localUser.getEmail();
                String localUserEmailUniqueID = getEmailAddressUniqueID(localUserEmail);
                String dbUsersRoot = "https://DATABASENAME.firebaseio.com/Users/";
                String dbUniqueRefForCurrentUser = dbUsersRoot + localUserEmailUniqueID +"/parishioners";
                DatabaseReference databaseReferenceCurrentUser = FirebaseDatabase.getInstance().getReferenceFromUrl(dbUniqueRefForCurrentUser);

                databaseReferenceCurrentUser.push().setValue(editTextNewMember.getText().toString().trim());
            }
        });
}

On clicking the Add Button, I'll have in my database something like this (supposing the EditText has in it the string 'capuccino'):

"luminittta" : {
      "parishioners" : {
        "-KX1GcEWPMy7oFWgt_3h" : "capuccino"

Now, my List will show 'capuccino' (since it's a realtime database my list will automatically get updated with the newly added value).

My question is: How can I implement next a delete functionality that when the user long clicks an item from the ListView it gets removed?

Entire Database looks like this:

{
  "Users" : {
    "davidivanmircea" : {
      "parishioners" : {
        "-KX1FNcgSXgsMNz6QRIS" : "Gus Crick",
        "-KX1FVIzzPM4nMrMvm9x" : "Florentino Williams",
        "-KX1FZ27M-KS5TQZQ76u" : "Marc Raff",
        "-KX1FbercKpPrl9r9tb4" : "Frederick Haddon",
        "-KX1FgguOlRRN4sZKS8Z" : "Cristobal Wolfe",
        "-KX1FkgwifQLIHplsZNx" : "Scott Nodal",
        "-KX1Fp64Sa2QD94GR9uK" : "Odis Nevers",
        "-KX1FrYK5PeuBucEiamY" : "Chauncey Mossman",
        "-KX1FvIBDSrvppC3e4Ip" : "Alfonso Ignacio",
        "-KX1Fy7dEHH8Z9JV-BRL" : "Douglas Hettinger",
        "-KX1WdtbV4PEiscJV6E_" : "Daniel Muresan",
        "-KX1WvYqekJZdWS6wGh6" : "Angelina Jolie"
      }
    },
    "luminittta" : {
      "parishioners" : {
        "-KX1GYuSsgmHyGk5LQLA" : "mocha",
        "-KX1G_Q130sWitNGzlAR" : "triplo",
        "-KX1GaPIhuIyhV4vmLGe" : "latte",
        "-KX1GcEWPMy7oFWgt_3h" : "capuccino",
        "-KX1Gf7TKY3N8IQETig-" : "machiatto",
        "-KX1Gh4KoYpcVpCDFI2x" : "cafe melange",
        "-KX1GoCutX3XO-CRWWB3" : "ristretto",
        "-KX1GpvdE5i9UR2ZaX0K" : "americano",
        "-KX1Grb8S5QZu4HT9cuW" : "espresso"
      }
    }
  }
}

Thank you very much for your help !

PS: I have modified my actual database name with 'DATABASENAME' inside the code.

回答1:

Change your "populateView" to this one:

@Override
protected void populateView(View v, String model, int position) {
    TextView textView = (TextView) v.findViewById(android.R.id.text1);
        textView.setText(model);
    v.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
         mRecycleViewAdapter.getRef(position).removeValue(); 
         Log.d("TAG", model + " removed from the list");                 
      }
   });
  }
};


回答2:

After reading the code Nirel and Frank provided, I changed my FirebaseListAdapter into a RecyclerView succesfully and implemented my Delete functionality (on clicking the item from the list).

For the record, RecyclerView does not come with an onClickListener by itself, so anyone who will be in the same situation as I was will need to implement it. I have used http://www.littlerobots.nl/blog/Handle-Android-RecyclerView-Clicks/ and it works like a charm.