简体   繁体   中英

How to remove the selected item from Arraylist<HashMap<String, String>> in android

I am using Arraylist < HashMap< String, String >> in ListView to archive multi-column(I just need two column, so I use HashMap). But when I am using remove method in context menu. It would always remove the last item in the list.

The code:

@Override
public boolean onContextItemSelected(MenuItem item) {
    final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
    switch (item.getItemId()) {
        case R.id.bc_contextmenu_delete:
            list.remove(info.position);
            adapter.notifyDataSetChanged();
            return true;
        default:
            return super.onContextItemSelected(item);
    }
}

What should I do to solve this problem to remove the selected one from the list?

Besides, I would also like to get those two values from the HashMap which in the ArrayList. Which code should I use here.

Here is an ArrayList:

PS4 4000<br>
PS5 5000<br>
XBOX 6000<br>

I would like to get PS4 and 4000.

Thanks all.

No need to wrap the HashMap into an ArrayList. HashMap itself is enough. If you want to remain the order, you should use LinkedHashMap . A side effect is that you cannot access elements by index, so you have to iterate over it to get the last item or the one by index.

So if you don't care about duplicates I would use ArrayList with as template a Pair or a custom Object. (Where I prefer a custom object to be more readable)

ArrayList<Pair<String,String>> consoles = new ArrayList<Pair<String,int>>();
consoles.Add(Pair.create("PS4", 4000));
consoles.Add(Pair.create("PS5 ", 5000));
consoles.Add(Pair.create("XBOX ", 6000));

And remove using index:

consoles.Remove(index);

As per your requirement, you can create a bean for same. ie DummyBean. it has two field like

class DummyBean{
String name;
String val;

--getter setter method
}

Use it into List<DummyBean> . In future if new column added than it is easy to add and expandable.

To store and retrieve your values from the Hashmap in ArrayList, You need to store the the HashMap values with keys to identify them

As with your example ,

PS4 4000
PS5 5000
XBOX 6000

  ArrayList<HashMap<String ,String>> list = new ArrayList<>();

    // to add item
    HashMap<String ,String> val = new HashMap<>();
    val.put("GAME", "PS4");
    val.put("NUMBER", "4000");
    list.add(val); //added to 0th index position

    val = new HashMap<>();
    val.put("GAME", "PS5");
    val.put("NUMBER", "5000");
    list.add(val); //added to 1st

    // to retrieve ps4 and 400
    String forPS4 = list.get(0).get("GAME");
    String for4000 = list.get(0).get("4000");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM