无法通过上下文菜单删除listView中的所选项目?

时间:2015-09-29 07:24:53

标签: android android-listview indexoutofboundsexception

我试图通过上下文菜单删除列表视图中的所选项目。

这是我的代码。

public class MainActivity extends AppCompatActivity 
{
EditText editText;
Button add;
ListView listView;
final DBFunctions db=new DBFunctions(MainActivity.this);
ArrayAdapter<String> adapter;
String[] values;

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

    editText= (EditText) findViewById(R.id.editText);
    add= (Button) findViewById(R.id.button);
    listView= (ListView) findViewById(R.id.listView);
    values=db.getAlldata();
    adapter=new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,values);
    listView.setAdapter(adapter);
    add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String name = editText.getText().toString();
            if (!name.equals("")) {
                editText.setText("");
                long check = db.insertData(name);
                if (check < 0) {
                    Toast.makeText(MainActivity.this, "Error in insert query", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, name + " inserted", Toast.LENGTH_SHORT).show();
                }
                adapter.notifyDataSetChanged();
            } else {
                editText.setError("this field is empty");
            }
        }
    });

    registerForContextMenu(listView);
}

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
{
    getMenuInflater().inflate(R.menu.menu_main, menu);
    super.onCreateContextMenu(menu, v, menuInfo);
}

@Override
public boolean onContextItemSelected(MenuItem item)
{
    int position=listView.getSelectedItemPosition();
    String data=values[position];                    //error line 
    Log.e("Value  ", data );
    Log.e("Position ", position+"" );
    switch (item.getItemId())
    {
        case R.id.delete_name:
            long check=db.deleteData(data);
            if(check<0)
            {
                Toast.makeText(MainActivity.this,"Error in query",Toast.LENGTH_SHORT).show();
            }
            else
            {
                adapter.notifyDataSetChanged();
                Toast.makeText(MainActivity.this,data+" deleted",Toast.LENGTH_SHORT).show();
            }
            return true;
        default :
            return super.onContextItemSelected(item);
    }
}
}

当我运行上面的代码时,我得到以下错误:

 java.lang.ArrayIndexOutOfBoundsException: length=3; index=-1
        at pack.madhan.listviewdemo.MainActivity.onContextItemSelected(MainActivity.java:72)
        at android.app.Activity.onMenuItemSelected(Activity.java:2628)
        at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:353)
        at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:144)
        at android.support.v7.internal.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:99)
        at com.android.internal.policy.impl.PhoneWindow$DialogMenuCallback.onMenuItemSelected(PhoneWindow.java:3864)
        at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:741)

是否可以通过上下文菜单删除列表视图中的所选项目? 请帮助我。

2 个答案:

答案 0 :(得分:0)

基于logstack,函数listView.getSelectedItemPosition()返回-1。

int position=listView.getSelectedItemPosition();

java.lang.ArrayIndexOutOfBoundsException: length=3; index=-1

-1不是正确的索引,并且是此OutOfBoundsException的原因。

我从未尝试跟踪列表中选择的最新元素,但您可以执行以下操作: 在MainActivity的开头添加一个变量来跟踪selectedItem;

// First item of the list is selected by defaul to avoid out of bound
int selectedItem = 0; 

使用onItemClickListener

更新此变量
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
   @Override
   public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
      selectedItem = id;
   }
});

答案 1 :(得分:0)

最后我找到了答案

错误代码:

int position=listView.getSelectedItemPosition();
String data=values[position];

更新代码:

AdapterView.AdapterContextMenuInfo info= (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();

String data=values[info.position];

其中 info.position 给出listView中项目的位置。 参考click here