从listview和hashmap中删除特定条目时出错

时间:2016-11-09 21:51:51

标签: android listview hashmap android-arrayadapter

尝试从listview和hashmap中删除特定条目时出现以下错误:

java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
                  at java.util.ArrayList.get(ArrayList.java:411)
                  at android.widget.ArrayAdapter.getItem(ArrayAdapter.java:349)
                  at android.widget.AdapterView.getItemAtPosition(AdapterView.java:790)
                  at com.example.cmmalli.helloworld.MainActivity.onContextItemSelected(MainActivity.java:120)
                  at android.app.Activity.onMenuItemSelected(Activity.java:3224)
                  at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:406)
                  at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:195)
                  at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:103)
                  at com.android.internal.policy.PhoneWindow$PhoneWindowMenuCallback.onMenuItemSelected(PhoneWindow.java:3722)
                  at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:761)
                  at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
                  at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:904)
                  at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:894)
                  at com.android.internal.view.menu.MenuPopup.onItemClick(MenuPopup.java:128)
                  at android.widget.AdapterView.performItemClick(AdapterView.java:310)
                  at android.widget.AbsListView.performItemClick(AbsListView.java:1155)
                  at android.widget.AbsListView$PerformClick.run(AbsListView.java:3126)
                  at android.widget.AbsListView$3.run(AbsListView.java:4041)
                  at android.os.Handler.handleCallback(Handler.java:751)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6077)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

我的代码是:

public class MainActivity extends AppCompatActivity {

ArrayAdapter adapter;
TextView user_name;
TextView user_amount;
ImageButton addbtn;
ListView listView;
HashMap<String, Double> myMap = new HashMap<String, Double>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    user_name = (TextView) findViewById(R.id.nameeditText);
    user_amount = (TextView) findViewById(R.id.amounteditText);
    addbtn = (ImageButton)findViewById(R.id.moreImageButton);
    listView = (ListView)findViewById(R.id.simple_list_item_1);
    registerForContextMenu(listView);

    adapter = new ArrayAdapter<User>(
            MainActivity.this,
            android.R.layout.simple_list_item_1);

    listView.setAdapter(adapter);

    addbtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String name = user_name.getText().toString();
            Double amount = Double.parseDouble(user_amount.getText().toString());
            adapter.add(new User(name, amount));
            adapter.notifyDataSetChanged();
            myMap.put(name,amount);

            Iterator myVeryOwnIterator = myMap.keySet().iterator();
            while(myVeryOwnIterator.hasNext()) {
                Toast.makeText(getBaseContext(), (String) myVeryOwnIterator.next(),
                        Toast.LENGTH_SHORT).show();
            }

        }
    });



}


@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    menu.setHeaderTitle("Options");
    if (v.getId()==R.id.simple_list_item_1) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_list, menu);
    }
}


@Override
public boolean onContextItemSelected(MenuItem item) {
    android.widget.AdapterView.AdapterContextMenuInfo info = (android.widget.AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
    switch(item.getItemId()) {
        case R.id.edit:
            //edit name or amount here
            return true;
        case R.id.delete:
            adapter.remove(listView.getItemAtPosition(info.position));
            adapter.notifyDataSetChanged();
            myMap.remove(listView.getItemAtPosition(info.position));
            return true;
        case R.id.deleteall:
            adapter.clear();
            adapter.notifyDataSetChanged();
            myMap.clear();
            return true;
        default:
            return super.onContextItemSelected(item);
    }
}


public class User {
    public String name;
    public double amount;

    public User(String name, double amount) {
        this.name = name;
        this.amount = amount;
    }

    @Override
    public String toString() {
        return format("%s : %.2f", this.name, this.amount);
    }
}

长按listview中的一行,它会提供编辑,删除和删除所有选项。删除所有选项都有效,但删除特定行的选项会产生错误。我不知道我哪里错了。建议将不胜感激。 我试图从用户获取User_name和amount,然后在listview中显示它并将键值对存储在hashmap中,以便也可以编辑它。

1 个答案:

答案 0 :(得分:0)

您的错误是适配器为空,因此您需要先添加一些数据才能开始删除它。

我不确定你为什么需要HashMap,但如果你想从适配器中删除一个元素,你可能需要ArrayList

(我重命名了ListView ID,因为它不是一个简单的列表项)

public class MainActivity extends AppCompatActivity {

    ArrayAdapter<User> adapter;
    List<User> users;   // added
    ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView = (ListView)findViewById(R.id.listView);
        registerForContextMenu(listView);

        users = new ArrayList<User>();   // added

        adapter = new ArrayAdapter<User>(
                MainActivity.this,
                android.R.layout.simple_list_item_1
                users);   // added

        listView.setAdapter(adapter);
        // listView.setOnLongClickListener...  // You also could use this...

我对上下文菜单没有多少经验,但我想象的是这样的事情

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    menu.setHeaderTitle("Options");
    if (v.getId()==R.id.listView) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_list, menu);
    }
}

@Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
    final int index = info.position;
    final User u = users.get(index);  // or adapter.getItem(index);

    switch(item.getItemId()) {
        case R.id.edit:
            //edit name or amount here
            return true;
        case R.id.delete:
            users.remove(index);
            adapter.notifyDataSetChanged();
            return true;
        case R.id.deleteall:
            users.clear();
            adapter.notifyDataSetChanged();
            return true;
        default:
            return super.onContextItemSelected(item);
    }
}