Deleting items from ListView with a contextmenu in Android?

∥☆過路亽.° 提交于 2019-12-01 01:50:58

This code should do the job:

adapter.remove(adapter.getItem(info.position));

I wrote above adapter code in my program, when i run program & delete item using context menu at that time force close window come

this is my code

public class ShowContextMenu extends ListActivity {

ArrayAdapter<String> adapter;



/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

   final String []s=(getResources().getStringArray(R.array.names));

   final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,s);

    setListAdapter(adapter);


    registerForContextMenu(getListView());
}

public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.context_menu, menu);
}






public boolean onContextItemSelected(MenuItem item) {
    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();

    String[] names = getResources().getStringArray(R.array.names);

    switch(item.getItemId()) {

    case R.id.edit:
        Toast.makeText(this, "You have chosen the " + getResources().getString(R.string.edit) + 
                " context menu option for " + names[(int)info.id],                          
                Toast.LENGTH_SHORT).show();



        return true;

    case R.id.save:
        Toast.makeText(this, "You have chosen the " + getResources().getString(R.string.save) + 
                " context menu option for " + names[(int)info.id],
                Toast.LENGTH_SHORT).show();
        return true;

    case R.id.delete:

// insert code here

adapter.remove(adapter.getItem(info.position));


        Toast.makeText(this, "You have chosen the " + getResources().getString(R.string.delete) + 
                " context menu option for " + names[(int)info.id],
                Toast.LENGTH_SHORT).show();

        return true;

    case R.id.view:

        Toast.makeText(this, "You have chosen the " + getResources().getString(R.string.view) + 
                " context menu option for " + names[(int)info.id],
                Toast.LENGTH_SHORT).show();
        return true;
    default:
        return super.onContextItemSelected(item);
    }
}

}

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