I'm pritty new to Android and I've got a little question.
I've got a Problem with my ContextMenu. I have filled my ListView with my database entries, now i wand if i longclick it, that the ContextMenu pops up and there i want to delete or to edit my databaseentries:
But I don't get how I can find out what entrie it is.
Here's my Code..
package de.retowaelchli.filterit.stats;
import de.retowaelchli.filterit.R;
import de.retowaelchli.filterit.database.ADFilterDBAdapter;
import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.SimpleCursorAdapter;
public class CreatedADFilters extends ListActivity {
//Variablen deklaration
private ADFilterDBAdapter mDbHelper;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
//Kontext-Menu registrieren
registerForContextMenu(findViewById(R.layout.list_layout));
//Hier wir die Datenbank aufgerufen
mDbHelper = new ADFilterDBAdapter(this);
mDbHelper.open();
fillData();
}
private void fillData() {
// Get all of the notes from the database and create the item list
Cursor c = mDbHelper.getAllADFilter();
startManagingCursor(c);
String[] from = new String[] { ADFilterDBAdapter.NAME, ADFilterDBAdapter.ROW_ID };
int[] to = new int[] { R.id.label };
// Now create an array adapter and set it to display using our row
SimpleCursorAdapter adname =
new SimpleCursorAdapter(this, R.layout.list_layout, c, from, to);
setListAdapter(adname);
mDbHelper.close();
}
//ContextMenu erstellen und definieren
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
if (v.getId() == R.layout.list_layout) {
getMenuInflater().inflate(R.menu.createdadmenu, menu);
}
super.onCreateContextMenu(menu, v, menuInfo);
}
public boolean onContextItemSelected(MenuItem item) {
final AdapterView.AdapterContextMenuInfo info =
(AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case R.id.delete_adfilter: {
deleteAD();
return true;
}
case R.id.edit_adfilter:{
editAD();
return true;
}
return super.onContextItemSelected(item);
}
}
// THIS IS THE PART I DONT KNOW HOW TO REALIZE
private void deleteAD(){
}
private void editAD(){
}
}
Thx for you Help in Advance!
best regards
safari
Your info local variable in onContextItemSelected() has an id data member which contains the _ID value from your Cursor. Here is a sample project demonstrating how to use that to delete an item based on a ListView context menu.
Related
I am studying how to use the contextual action mode according to the official document at http://developer.android.com/guide/topics/ui/menus.html#CAB
However, everything works fine except for that the selected item cannot keep highlighted as expected(am I supposed to?) when I show the contextual action mode.
I tried to set the list selector with selective drawables, set the item view background with selective drawables but all ended in vain.
Could anybody help me out?
My code is listed below:
import com.robin.huangwei.omnigif.content.GifStore;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
public class MainActivity extends ActionBarActivity implements LoaderCallbacks<Cursor>, OnItemLongClickListener{
private static final int LOADER_ID_GIFIMAGES = 0;
private SimpleCursorAdapter mAdapter;
private ListView mListView;
private ActionMode mActionMode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportLoaderManager().initLoader(LOADER_ID_GIFIMAGES, null, this);
String[] from = new String[] {GifStore.GifImages.Media._ID, GifStore.GifImages.Media.DISPLAY_NAME};
int[] to = new int[] {R.id.item_icon, R.id.item_name};
mAdapter = new SimpleCursorAdapter(this, R.layout.icon_text_item, null, from, to, 0);
mListView = (ListView) findViewById(R.id.listview);
mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
mListView.setAdapter(mAdapter);
mListView.setOnItemLongClickListener(this);
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String[] projection = {MediaStore.Images.Media._ID, MediaStore.Images.Media.DISPLAY_NAME};
CursorLoader cursorLoader = new CursorLoader(this, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null, null, null);
return cursorLoader;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor c) {
mAdapter.swapCursor(c);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
mAdapter.swapCursor(null);
}
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
if (mActionMode != null) {
return false;
}
mActionMode = startSupportActionMode(mActionModeCallback);
view.setSelected(true);
mListView.setDrawSelectorOnTop(true);
return true;
}
private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
/**
* Called each time the action mode is shown. Always called after
* onCreateActionMode, but may be called multiple times if the mode is invalidated.
*/
#Override
public boolean onPrepareActionMode(ActionMode arg0, Menu arg1) {
// TODO Auto-generated method stub
return false;
}
/*
* // Called when the user exits the action mode
*/
#Override
public void onDestroyActionMode(ActionMode arg0) {
mActionMode = null;
}
/*
* Called when the action mode is created; startActionMode() was called
*/
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.menu_list_item_context, menu);
return true;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_list_item_context_edit:
break;
case R.id.menu_list_item_context_star_unstar:
break;
case R.id.menu_list_item_context_delete:
break;
default:
return false;
}
mode.finish();
return true;
}
};
}
I have a ListView with a button on it. When I click the Button I have a AlertDialog with a EditText on it that pops up. When the users enters data into the EditText on the AlertDialog it goes out and updates a SQLite Database. When the original ListView shows back up it is blank. When I exit the app and return the app the data entered in the AlertDialog shows up. I need the new data to show up after the AlertDialog closes.
package com.wmason.testcreator;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.os.Bundle;
//import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import android.app.ListActivity;
import android.widget.Button;
import android.content.Intent;
import android.content.res.AssetManager;
import android.database.Cursor;
public class MainActivity extends ListActivity {
private DbManagement mdbManager;
private TestProcessor tp;
SimpleCursorAdapter notes;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lookup);
mdbManager = new DbManagement(this);
tp = new TestProcessor(this);
mdbManager.open();
fillData();
Button testingCsv =(Button)findViewById(R.id.btnTestCsv);
testingCsv.setOnClickListener(ChokeSlam);
fillData();
}
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
fillData();
}
private OnClickListener ChokeSlam = new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
AssetManager aM = getAssets();
try{
//This line of code opens the AlertDialog
tp.ProcessInboundStream(aM,"Book1.csv",mdbManager);
fillData();
}
catch(Exception ex){
System.out.println(ex.toString());
}
}
};
protected void onListItemClick(ListView l, View v, int position, long id) {
/*
boolean b;
b=mdbManager.deleteTests(id);
*/
//fillData();
Intent i = new Intent(this,DisplayTests.class);
i.putExtra("ID",Long.toString(id));
startActivity(i);
}
private void fillData(){
Cursor testCursor = mdbManager.fetchAllTests();
startManagingCursor(testCursor);
// Create an array to specify the fields we want to display in the list (only TITLE)
String[] from = new String[]{DbManagement.Gen_Test_Name};
// and an array of the fields we want to bind those fields to (in this case just text1)
int[] to = new int[]{R.id.text1};
//R.layout.
// Now create a simple cursor adapter and set it to display
notes =
new SimpleCursorAdapter(this, R.layout.testrows, testCursor, from, to);
setListAdapter(notes);
notes.notifyDataSetChanged();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
They way I figured this out was to use the following method
#Override
public void onWindowFocusChanged(boolean hasFocus) {
// TODO Auto-generated method stub
super.onWindowFocusChanged(hasFocus);
fillData();
}
Basically as soon the AlertDialog closes it fires off this method and it goes out and re-populates the ListView
Try this....
listview.setAdapter(adapter);
adapter.notifyDataSetChanged();
I do something like this in the Activity file where the dialog is required.
AlertDialog dialog = dialogViewer.returnEditDialog();
dialog.show();
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
refreshView();
}
});
The OnDismissListener is called every time an ALertDialog fragment is closed.
So I have a weird problem. I have 2 Activities I'm working on. One of the Activities displays a ListView whose data is grabbed via a long Extra I use to fetch the results via a WHERE clause in the database.query. The other Activity is called when a ListView item is clicked, allowing someone to add something to the database for the ListView.
The activity names are DaysActivity.java (the activity with the listview) and DayAddActivity.java (the Activity that allows someone to add a day, which then shows up in the DaysActivity.java ListView).
The problem I'm having is, when I finish() DayAddActivity.java it goes back to DaysActivity and the ListView is still there fully populated. However, if I hit the back button in DayAddActivity.java (the button to the left of the title in the action bar with my app icon), when it goes back to DaysActivity.java, the ListView is empty/gone.
Heres the code for both:
DaysActivity.java:
package com.gauvion.gfit;
import android.annotation.SuppressLint;
import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
public class DaysActivity extends ListActivity {
private DaysDataSource datasource;
private SimpleCursorAdapter dataAdapter;
private boolean isEditing = false;
private Toast toast_deleted;
private String[] columns = new String[] { MySQLiteHelper.COLUMN_NAME, MySQLiteHelper.COLUMN_DAY };
private int[] to;
private long routineDataID;
private String routineDataName;
#SuppressLint("ShowToast")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_days);
routineDataID = getIntent().getLongExtra("routineDataID", 0);
routineDataName = getIntent().getStringExtra("routineDataName");
setTitle(routineDataName);
toast_deleted = Toast.makeText(this, "", Toast.LENGTH_SHORT);
datasource = new DaysDataSource(this);
datasource.open();
Cursor cursor = datasource.fetchAllDays(routineDataID);
to = new int[] { R.id.listitem_day_name, R.id.listitem_day_day };
dataAdapter = new SimpleCursorAdapter(this, R.layout.listitem_day, cursor, columns, to, 0);
setListAdapter(dataAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_days, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Cursor cursor = datasource.fetchAllDays(routineDataID);
switch (item.getItemId()) {
case R.id.button_days_add:
Intent startDayAdd = new Intent(this, DayAddActivity.class);
startDayAdd.putExtra("routineDataID", routineDataID);
this.startActivity(startDayAdd);
return true;
case R.id.button_days_edit:
to = new int[] { R.id.listitem_day_edit_name, R.id.listitem_day_edit_day };
dataAdapter = new SimpleCursorAdapter(this, R.layout.listitem_day_edit, cursor, columns, to, 0);
setListAdapter(dataAdapter);
isEditing = true;
invalidateOptionsMenu();
return true;
case R.id.button_days_edit_done:
to = new int[] { R.id.listitem_day_name, R.id.listitem_day_day };
dataAdapter = new SimpleCursorAdapter(this, R.layout.listitem_day, cursor, columns, to, 0);
setListAdapter(dataAdapter);
isEditing = false;
invalidateOptionsMenu();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
menu.findItem(R.id.button_days_edit).setVisible(!isEditing);
menu.findItem(R.id.button_days_edit_done).setVisible(isEditing);
return true;
}
#Override
protected void onResume() {
datasource.open();
Cursor cursor = datasource.fetchAllDays(routineDataID);
dataAdapter.changeCursor(cursor);
super.onResume();
}
#Override
protected void onPause() {
datasource.close();
super.onPause();
}
}
DayAddActivity.java:
package com.gauvion.gfit;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import android.support.v4.app.NavUtils;
public class DayAddActivity extends Activity {
private RoutinesDataSource datasource;
private EditText dayName;
private Spinner dayDay;
private Button saveButton;
private long routineDataID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_day_add);
routineDataID = getIntent().getLongExtra("routineDataID", 0);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_day_add, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
public void cancelDay(View view) {
this.finish();
}
}
The cancelDay() function is called when a "Cancel" button is clicked in activity_day_add.xml. Like I said, when I click the "Cancel" button inside of DayAddActivity.java, it goes back to DaysActivity.java and the ListView is fine. All data is there. However, if I press the back button in the action bar (the button containing a back arrow and my app icon beside the title of the Activity) the ListView for DaysActivity.java is empty/gone, and the title is also empty (because this is also generated through an Extra String value).
Your cursors are not managed by the activity, this can cause a memory leak or even ANR. You should consider using a loader to populate a list using a cursor. You can find an example here :http://developer.android.com/guide/components/loaders.html.
Loaders work better as they don't freeze the app when the connexion to the database is obtained and they will be passed from one instance of your activity to another, preventing memory leaks and reusing resources.
But again, as in your previous post : Extras seem to be lost onResume(), you should understand the link between onSaveInstanceState and onCreate to pass arguments to the future self of your activity. Look at this post, the answer with the biggest score : onSaveInstanceState () and onRestoreInstanceState ().
It seems like your Context has some problems in "this.startActivity(startDayAdd);" line. try using "DaysActivity.this.startActivity(startDayAdd);". if it doesnot work then use breakpoints to see line by line execution.
on my application i want to click the list item and make some changes like deleting or updating the item.but i could not implemented the other codes to my code.so little help will be useful. here is my code
package com.example.todolist;
import java.util.ArrayList;
import java.util.Collection;
import android.os.Bundle;
import android.provider.Contacts;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class MainActivity extends Activity implements OnClickListener,OnKeyListener,OnInitListener {
EditText txtitem;
ListView listitem;
TextToSpeech talker;
ArrayList<String> todolist;
ArrayAdapter<String> arrayadapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtitem = (EditText) findViewById(R.id.txtitem);
listitem = (ListView) findViewById(R.id.listitem);
talker = new TextToSpeech(this, this);
txtitem.setOnKeyListener(this);
todolist = new ArrayList<String>();
arrayadapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,todolist);
listitem.setAdapter(arrayadapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.main, menu);
MenuItem toAdd = menu.add("AddItem");
MenuItem toDelete = menu.add("DeleteItem");
MenuItem toSave = menu.add("SaveItem");
MenuItem toExit = menu.add("ExitItem");
MenuItem toUpdate = menu.add("UpdateItem");
return true;
}
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
return false;
}
#Override
public void onClick(DialogInterface dialog, int which) {
}
public boolean onOptionsItemSelected(MenuItem item){
super.onOptionsItemSelected(item);
if(item.getTitle().equals("AddItem")){
todolist.add(txtitem.getText().toString());
arrayadapter.notifyDataSetChanged();
txtitem.setText("");
}
if(item.getTitle().equals("DeleteItem")){
String x = txtitem.getText().toString();
int y = Integer.parseInt(x);
todolist.remove(y-1);
arrayadapter.notifyDataSetChanged();
txtitem.setText("");
}
if(item.getTitle().equals("SaveItem")){
say("Save Complete");
arrayadapter.notifyDataSetChanged();
}
if (item.getTitle().equals("ExitItem")){
talker.speak("Are you sure you want to close this activity?",TextToSpeech.QUEUE_FLUSH,null);
onBackPressed();
}
if(item.getTitle().equals("UpdateItem")){
String x = txtitem.getText().toString();
int y = Integer.parseInt(x);
arrayadapter.notifyDataSetChanged();
txtitem.setText(todolist.get(y-1));
todolist.remove(y-1);
}
return true;
}
public void say(String text2say){
talker.speak(text2say, TextToSpeech.QUEUE_FLUSH, null);
}
#Override
public void onInit(int status) {
}
#Override
public void onDestroy() {
if (talker != null) {
talker.stop();
talker.shutdown();
}
super.onDestroy();
}
}
#Override
public void onBackPressed()
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Closing Activity")
.setMessage("Are you sure you want to close this activity?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
runOnUiThread(new Runnable() {
#Override
public void run() {
say("Bye");
}
});
}
})
.setNegativeButton("No", null)
.show();
}
this code takes the list's elemnt number and delete's it.but i want to click and delete or update.son little help will be useful.thank you already
To remove the desired item from the list using the remove() method of your ArrayAdapter.
A possible way to do that would be:
Object toRemove = arrayAdapter.getItem([POSITION]);
arrayAdapter.remove(toRemove);
Another way would be to modify the ArrayList and call notifyDataSetChanged() on the ArrayAdapter.
arrayList.remove([INDEX]);
arrayAdapter.notifyDataSetChanged();
To Add items you can do something like this :
on a click of button take text from edittext and add it as an item on list
/** Reference to the button of the layout main.xml */
Button btn = (Button) findViewById(R.id.btnAdd);
/** Defining the ArrayAdapter to set items to ListView */
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
/** Defining a click event listener for the button "Add" */
OnClickListener listener = new OnClickListener() {
#Override
public void onClick(View v) {
EditText edit = (EditText) findViewById(R.id.txtItem);
list.add(edit.getText().toString());
edit.setText("");
adapter.notifyDataSetChanged();
}
};
/** Setting the event listener for the add button */
btn.setOnClickListener(listener);
Read official android docs here 1 and 2 for handling click of menu items ...
What you want to do is set the itemClickListener(). This is done by something like this:
list.setOnItemClickListner(new OnItemClickListener(){
onItemClick(AdapterView<?> parent, View view, int position, long id)
{
//Do stuff here.
}
});
From that block, you just need to call your delete statement. Alternatively, you could have your class use the AdapterView.OnItemClickListener interface, and put the routine there, then changing the command to list.setOnItemClickListner(this);
So i am preety new with this SQLite i finaly managed to create base and work with it etc. Now i created ContextMenu thath you will be able to delete item from listView on which context menu was opened. Here is my current code.
import java.util.List;
import java.util.Random;
import android.app.ListActivity;
import android.os.Bundle;
import android.text.Editable;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuInflater;
import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import android.view.MenuItem;
public class Ann extends ListActivity{
private CommentsDataSource datasource;
EditText edit;
ListView bump;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ann);
datasource = new CommentsDataSource(this);
datasource.open();
List<Comment> values = datasource.getAllComments();
ArrayAdapter<Comment> adapter = new ArrayAdapter<Comment>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
registerForContextMenu(getListView());
}
public void onClick(View view) {
#SuppressWarnings("unchecked")
ArrayAdapter<Comment> adapter = (ArrayAdapter<Comment>) getListAdapter();
Comment comment = null;
switch (view.getId()) {
case R.id.add:
edit = (EditText)findViewById(R.id.editTxt);
Editable txt=(Editable)edit.getText();
String vnos = txt.toString();
comment = datasource.createComment(vnos);
adapter.add(comment);
edit.setText("");
break;
}
adapter.notifyDataSetChanged();
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo){
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
#Override
protected void onResume() {
datasource.open();
super.onResume();
}
#Override
protected void onPause() {
datasource.close();
super.onPause();
}
}
Now i know thath i need to make method for public boolean onContextItemSelected(MenuItem item)
but how to manage now to delete item which was selected.
Can I ask why you don't use a SimpleCursorAdapter to create the list? It looks like you're getting a cursor and turning into an array... why take that extra step? It's useful in that if you make an addition/deletion to the database, you can simply use the requery() method to regenerate/update the list.
Anyway, should you decide to go with a SimpleCursorAdapter, onContextItemSelected(MenuItem item) would be the way to go. An example from one of my projects:
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
if (item.getTitle() == "Delete Member") {
mDbHelper.deleteMember(info.id);
mMemberCursor.requery();
return true;
}
return super.onContextItemSelected(item);
}
Note that I created my menu view programatically, so you may need to change the if statement to something that will work better for your set-up with an inflated menu resource.
info.id is the row id from the database that represents the line of the list you clicked.
mDbHelper.deleteMember() is a method from my database helper for deleting records.
Hope this helps!
The context menu is not listItem specific, ie. id does not know which item was clicked.
Go for an onItemClicked or onItemLongClick version.
To do the latter implement the onItemLongClick interface on you activity
public class Ann extends ListActivity implements OnItemLongClickListener
and add the onItemLongClick method
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
// do something with your datasource and the position
return false;
}