Delete item from ListView using onCreateContextMenu - android

How to delete item from ListView using onCreateContextMenu? There is some problem in the code below. Any solution?
When item in listview is long pressed a menu popups in which there is an option of delete.
public class ContextMenuTest extends AppCompatActivity {
ListView listView;
String []name={"ANKUSH", "ANOUSHKA", "SHIVA", "SOMANSHU"};
String current;
ArrayAdapter<String> adapter;
int pos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_context_menu_test);
listView = (ListView) findViewById(R.id.lvContextMenu);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, name);
listView.setAdapter(adapter);
registerForContextMenu(listView);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("SELECT OPTION");
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_test, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId())
{
case R.id.delete:
adapter.remove(adapter.getItem(info.position));
break;
}
return true;
}
}

In the onContextItemSelected method, add adapter.notifyDataSetChanged() to notify the adapter of changes to the data.
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId())
{
case R.id.delete:
adapter.remove(adapter.getItem(info.position));
adapter.notifyDataSetChanged();
break;
}
return true;
}

This Works
public class ContextMenuTest extends AppCompatActivity {
ListView listView;
List<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_context_menu_test);
listView = (ListView) findViewById(R.id.lvContextMenu);
list.add("ANKUSH");
list.add("ANOUSHKA");
list.add("SHIVA");
list.add("SOMANSHU");
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
listView.setAdapter(adapter);
registerForContextMenu(listView);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("SELECT OPTION");
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_test, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId())
{
case R.id.delete:
list.remove(info.position);
adapter.notifyDataSetChanged();
return true;
default:
return super.onContextItemSelected(item);
}
}
}

Related

How to Have the item in the listview after clicked

I'm new in Android, I have a listview of items, and I have created a popup menu, when the user press a row he must have an item in a other activity.
my problem is, he sends me always the first item... no matter where I click in the listview.
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
final ListAdapter adapter = new SimpleAdapter(busqueda.this, productos,
R.layout.list_layout, new String[]{"codigo", "descrip", "precio", "fisicolug"},
new int[]{R.id.txtCodigo, R.id.txtDescrip, R.id.txtPrecio, R.id.Stock});
lista.setAdapter(adapter);
registerForContextMenu(lista);
registerForContextMenu(textView);
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
MenuInflater inflate = getMenuInflater();
if (v.getId() == R.id.listView) {
inflate.inflate(R.menu.menu_main, menu);
}
}
public boolean onContextItemSelected(final MenuItem item) {
switch (item.getItemId()) {
case R.id.masIn:
TextView textView = (TextView) findViewById(R.id.txtCodigo);
String text = textView.getText().toString();
Intent intent;
intent = new Intent(getApplicationContext(), Resultado.class);
intent.putExtra("CODIGO", text);
startActivity(intent);
super.onContextItemSelected(item);
}
return true;
}
By using listview setOnItemClickListener() you can handle the click event of listview
lista.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});

multiple listview in one activity with contextmenu for each of listview

I have multiple ListView in one activity with ContextMenu for each one of ListView.
Actually it should work fine with all the 7 ListViews,but it work for only Seventh List
this is my code.
ArrayAdapter<Course> adapter;
for(int i=0;i<7;i++){
courses = db.findFiltered(String.format("day == %d ", i), "startTime ASC");
ListView lv1 = (ListView) findViewById (arrayList[i]);
registerForContextMenu(lv1);
lv1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
});
adapter = new CourseListAdapter(this, courses);
lv1.setAdapter(adapter);
}
#Override
public void onCreateContextMenu(android.view.ContextMenu menu, View v, ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.contextmenu, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case R.id.editItem:
//do something
return true;
case R.id.showItem:
//do something
return true;
case R.id.deleteItem:
db.removeCourse(adapter.getItem(info.position);
adapter.remove(adapter.getItem(info.position));
return true;
default:
return super.onContextItemSelected(item);
}
}
please help
Adapter instance is set to last iteration ListView object. This is quick code change. Try this:
private ArrayAdapter<Course> selectedListViewAdapter;
...
for(int i=0;i<7;i++){
courses = db.findFiltered(String.format("day == %d ", i), "startTime ASC");
ListView lv1 = (ListView) findViewById (arrayList[i]);
registerForContextMenu(lv1);
lv1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
});
ArrayAdapter<Course> adapter = new CourseListAdapter(this, courses);
lv1.setAdapter(adapter);
}
#Override
public void onCreateContextMenu(android.view.ContextMenu menu, View v, ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.contextmenu, menu);
try {
ListView selectedListView = (ListView)v;
selectedListViewAdapter = (ArrayAdapter<Course>)selectedListView.getAdapter();
} catch(ClassCastException e) {
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case R.id.editItem:
//do something
return true;
case R.id.showItem:
//do something
return true;
case R.id.deleteItem:
if(null != selectedListViewAdapter) {
db.removeCourse(selectedListViewAdapter.getItem(info.position);
selectedListViewAdapter.remove(selectedListViewAdapter.getItem(info.position));
}
return true;
default:
return super.onContextItemSelected(item);
}
}

Why the contextmenu isn't working?

I have a listview with a custon adapter. I have to put a context menu for it, but it's not working. And I put the onItemLongClick to the list and it's not working too. I don't know how to trigger the contextmenu. If I have to click on an item or long click on it. I do register a long click to get the id from the item.
EDIT I think i figure out whats the problem. I have a button on my item listview. I remove this button from the layout and the context menu worked fine. But I need this button. Why the button was causing problem in the context menu?
This is the class:
public class HistoricoDespesasActivity extends Activity {
Helper h;
AlphaAnimation buttonClick;
DespesasDAO dDAO;
ListView lv;
DespesaHistoricoAdapter adapter;
int idDespesasSelecionada;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_historico_despesas);
lv = (ListView)findViewById(R.id.lvHistoricoDespesas);
TextView tvMarcaModelo = (TextView)findViewById(R.id.tvMarcaModeloCabecalho);
TextView tvApelido = (TextView)findViewById(R.id.tvApelidoCabecalho);
tvApelido.setVisibility(View.INVISIBLE);
tvMarcaModelo.setVisibility(View.INVISIBLE);
buttonClick = new AlphaAnimation(1, 0.5f);
h = new Helper(this);
h.mostraVeiculoAtivo();
adapter = new DespesaHistoricoAdapter(this);
dDAO = new DespesasDAO(this);
dDAO.open();
Cursor cursor = dDAO.consultarTodasDespesasByIdVeiculo(h.getId());
int id;
String data;
String tipoDespesa = null;
double valor;
int tipo = 0;
if(cursor != null && cursor.moveToFirst()){
do {
id = cursor.getInt(cursor.getColumnIndex(DespesasDAO.COLUNA_ID));
data = cursor.getString(cursor.getColumnIndex(DespesasDAO.COLUNA_DESPESA_DATA));
tipo = cursor.getInt(cursor.getColumnIndex(DespesasDAO.COLUNA_ITEM_ID));
valor = cursor.getDouble(cursor.getColumnIndex(DespesasDAO.COLUNA_DESPESA_VALOR));
if(tipo == 1){
tipoDespesa = "Pedágio";
} else if(tipo == 2){
tipoDespesa = "Estacionamento";
} else if(tipo == 3){
tipoDespesa = "Lavagem";
} else if(tipo == 4){
tipoDespesa = "Diversos";
}
adapter.addDespesa(id, tipoDespesa, data, valor);
} while (cursor.moveToNext());
cursor.close();
dDAO.close();
lv.setAdapter(adapter);
}
lv.setLongClickable(true);
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
idDespesasSelecionada = (Integer) parent.getItemAtPosition(position);
return true;
}
});
registerForContextMenu(lv);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Despesas");
menu.add(0, v.getId(), 0, "Deletar");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
if(item.getTitle().equals("Deletar")){
dDAO.open();
dDAO.removerDespesasById(idDespesasSelecionada);
dDAO.close();
}
onCreate(new Bundle());
return super.onContextItemSelected(item);
}
#Override
protected void onResume() {
onCreate(new Bundle());
super.onResume();
}
}
Remove your setOnItemLongClickListener of listView and replace onContextItemSelected with this
#Override
public boolean onContextItemSelected(MenuItem item)
{
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
if(item.getTitle().equals("Deletar"))
{
dDAO.open();
dDAO.removerDespesasById(info.position);
dDAO.close();
}
return true;
}
change onCreateContextMenu like this :
#Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater =getMenuInflater();
inflater.inflate(R.menu.more_tab_menu, menu);
}
see this topic :
Android, How to create Context Menu...
EDIT :
use button. image Button and list view is clickable. if you use Button and set android:focusable="false" android:focusableInTouchMode="false" work fine.

onContextItemSelected does not get called in a DialogFragment

I have a dialog that shows a list of items, I need to be able to edit/delete items in this list so I put a context menu in so when the user long presses on an item it they can choose what they want to do (edit or delete the item).
The problem is that onContextItemSelected never gets called when an item in the context menu is selected.
I checked to see if maybe the activity that created the dialog fragment is getting the callback but that is not either so why is there it not getting called? Can you not do a context menu in a dialog?
public class TypesDialogList extends DialogFragment implements LoaderManager.LoaderCallbacks<Cursor>,OnItemClickListener,OnCreateContextMenuListener{
ListView lv;
SimpleCursorAdapter mAdapter;
private int EDIT_TYPE = 1;
private int DELETE_TYPE = 2;
OnEditType mType;
public Dialog onCreateDialog(Bundle state){
final View v = getActivity().getLayoutInflater().inflate(R.layout.layer_dialog_layout, null, false);
lv = (ListView)v.findViewById(R.id.listView1);
lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
lv.setOnItemClickListener(this);
lv.setOnCreateContextMenuListener(this);
return new AlertDialog.Builder(getActivity()).setView(v).setPositiveButton("Add Type", new OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
}
}).setTitle("Type's").create();
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo){
super.onCreateContextMenu(menu, v, menuInfo);
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
long id = info.id;
if(id > 3){
menu.setHeaderTitle("Type Menu");
menu.add(Menu.NONE, EDIT_TYPE, 1, "Edit");
menu.add(Menu.NONE, DELETE_TYPE, 2, "Delete");
}else{
Toast.makeText(getActivity(),"Cannot edit type",Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
super.onContextItemSelected(item);
AdapterView.AdapterContextMenuInfo oMenuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
long id = oMenuInfo.id;
if(item.getItemId() == EDIT_TYPE){
}else if(item.getItemId() == DELETE_TYPE){
}
return true;
}
}
For anybody still looking for a workaround, I just solved this problem by creating an anonymous OnMenuItemClickListener that delegates back to onContextItemSelected(MenuItem item) and setting it on all the items in my menu.
#Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) {
// Creation/inflate menu here
OnMenuItemClickListener listener = new OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
onContextItemSelected(item);
return true;
}
};
for (int i = 0, n = menu.size(); i < n; i++)
menu.getItem(i).setOnMenuItemClickListener(listener);
}

how to get position in on context item selected in android?

setListAdapter(new ArrayAdapter<String>(this,R.layout.custom_list_item, r));
protected void onListItemClick(ListView list, View view, int position, long id) {
super.onListItemClick(list, view, position, id);
fname=r.get(position);
the above code I got position and name also from array adapter
Like, I need get these all are the values in context menu how can I get it
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Playlist Option");
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
public boolean onContextItemSelected(MenuItem item) {
// here I select the particular list value, that the value position I need that is only I delete that position from server. what are the data i fetch here? and its possible to get position from array list?
}
You can use AdapterContextMenuInfo
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case R.id.delete:
String itemName = r.get[(int) info.id]; // This item you will delete
// from list
return true;
}
}
public class DataDemo extends Activity {
public ArrayList<HashMap<String, String>> ContactList = new ArrayList<HashMap<String, String>>();
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_PHNO = "phNo";
private static int itemIndex;
private ListView lst;
private List<Contact> contacts;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_database_demo);
lst = (ListView) findViewById(R.id.lstContact);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
super.onCreateContextMenu(menu, v, menuInfo);
if (v.getId() == R.id.lstContact) {
menu.setHeaderIcon(R.drawable.message);
menu.setHeaderTitle("Contacts");
menu.add(0, 1, Menu.NONE, "Edit Contact");
menu.add(0, 2, Menu.NONE, "Delete Contact");
menu.add(0, 3, Menu.NONE, "Cancel");
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
// TODO Auto-generated method stub
AdapterView.AdapterContextMenuInfo menuInfo;//you can select on context item selected
menuInfo = (AdapterContextMenuInfo) item.getMenuInfo();
itemIndex = menuInfo.position;//you will get position of selected item
final Contact con = contacts.get(itemIndex);
switch (item.getItemId()) {
case 1:
Intent editIntent = new Intent(DataDemo.this, UpdateContact.class);
editIntent.putExtra(TAG_ID, con.getID());
editIntent.putExtra(TAG_NAME, con.getName());
editIntent.putExtra(TAG_PHNO, con.getPhNo());
startActivity(editIntent);
break;
case 2:
new AlertDialog.Builder(this)
.setIcon(R.drawable.document_delete)
.setTitle("Confirm Delete")
.setMessage("Are you sure?")
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
DatabaseHandler db = new DatabaseHandler(
DataDemo.this);
db.DeleteContact(con);
Toast.makeText(DataDemo.this, con.getName() + " Deleted",
Toast.LENGTH_SHORT).show();
fillList();
}
}).setNegativeButton("No", null).show();
break;
default:
break;
}
return super.onContextItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem addNew = menu.add(0, 1, 0, "Create Contact");
addNew.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// TODO Auto-generated method stub
Intent iCreate = new Intent(DataDemo.this, CreateContact.class);
startActivity(iCreate);
return true;
}
});
return true;
}
protected void fillList() {
DatabaseHandler db = new DatabaseHandler(this);
ListAdapter adap;
ContactList.clear();
contacts = db.ReadAllContact();
for (Contact cn : contacts) {
HashMap<String, String> hmap = new HashMap<String, String>();
hmap.put(TAG_NAME, cn.getName());
hmap.put(TAG_PHNO, cn.getPhNo());
ContactList.add(hmap);
adap = new SimpleAdapter(this, ContactList,
R.layout.list_item_view,
new String[] { TAG_NAME, TAG_PHNO }, new int[] {
R.id.lstName, R.id.lstPhNo });
lst.setAdapter(adap);
registerForContextMenu(lst);
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
fillList();
}
}

Categories

Resources