Delete from database SQLite Android - android

I have a problem. I try to delete the record from the database. I have no idea, but how to do it. I tried something like this, but not quite work.
The basic gist is that I trying to delete from the database based on list item position, not database row ID. How delete base database row ID?
ListView listawszystkich;
public int pozycja;
DatabaseDEO db = new DatabaseDEO(this);
final String[] skad = new String[]{Database.tables.Transakcje.Kolumny.kwota, Database.tables.Transakcje.Kolumny.data, Kategorie.KOLUMNY.nazwa_kategorii, Database.tables.Transakcje.Kolumny.komentarz};
final int[] dokad = new int[]{R.id.kwotaglowna,R.id.dataglowna,R.id.kategoriaglowna,R.id.komentarzglowny};
private SimpleCursorAdapter adapterspinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transakcje2);
listawszystkich = (ListView) findViewById(R.id.listawszystkich);
listawszystkich.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
pozycja = position+1;
}
});
Cursor kursorwszystkie = db.wszystkietransakcje();
adapterspinner = new SimpleCursorAdapter(getApplicationContext(), R.layout.activity_transakcje,kursorwszystkie,skad, dokad,0);
adapterspinner.notifyDataSetChanged();
listawszystkich.setAdapter(adapterspinner);
registerForContextMenu(listawszystkich);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if (v.getId()==R.id.listawszystkich) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_list,menu);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case R.id.delete:
db.usuwanietransakcji(pozycja);
Transakcje.this.recreate();
Toast.makeText(getApplicationContext(), "Delete", Toast.LENGTH_SHORT).show();
default:
return super.onContextItemSelected(item);
}
Method to delete row (in DatabaseDEO):
public void usuwanietransakcji(int id_transakcji){
SQLiteDatabase db = DbHelper.getWritableDatabase();
db.execSQL("DELETE FROM " + Transakcje.NAZWA_TABELI+ " WHERE "+Transakcje.Kolumny.id_transakcji+"='"+id_transakcji+"'");
db.close();
}

Looks like you're trying to delete from the database based on list position rather than row ID:
db.usuwanietransakcji(pozycja);
I'm guessing id_transakcji is a unique value similar to a row ID? First you'll need to declare Cursor kursorwszystkie as a member variable outside of the onCreate method, but still populate it on the same line.
In onContextItemSelected() you'll need to query your cursor again:
case R.id.delete: {
// Move to the selected row
kursorwszystkie.moveToPosition(info.position);
// Get the column ID of id_transakcji
final int col_id = kursorwszystkie.getColumnIndex(Database.tables.Transakcje.Kolumny.id_transakcji);
// Get id_transakcji
final int id_transakcji = kursorwszystkie.getInt(col_id);
// Query the database
db.usuwanietransakcji(id_transakcji);
Transakcje.this.recreate();
Toast.makeText(getApplicationContext(), "Delete", Toast.LENGTH_SHORT).show();
break;
}
Note the addition of {} as I'm declaring a variable inside a switch case. Also add a break; at the end of the case so the code doesn't fall through into the default block. Let me know if that works.

Related

Fetching row id from SQLite database on clicking a listview item

I have populated listview from database using ArrayAdapter, i want to get the database-row id of the list item when i click the the item. I have searched many hours, but i couldn't get the answer because i am beginner.
here is my main.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView=findViewById(R.id.quote_list);
registerForContextMenu(listView);
DatabaseAccess datac= DatabaseAccess.getInstance(getApplicationContext());
datac.open();
final ArrayList<String> thelist = new ArrayList<>();
Cursor data=datac.getquotes();
while(data.moveToNext()){
thelist.add(data.getString(2));
ListAdapter listAdapter = new ArrayAdapter<>(this,R.layout.textcenter,R.id.textitem,thelist);
listView.setAdapter(listAdapter);
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater menuInflater=getMenuInflater();
menuInflater.inflate(R.menu.my_contextual_menu,menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info =(AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
return super.onContextItemSelected(item);
}
}
Try in this way,
1. When you click on the item of list view, you will get the id.
2. get the string value from that index and call a method where send collected string as a parameter and fire a query in that method like
return db.rawQuery("select row_id from your_tableName where string_columnName="+your_passed_string+";",null);
Collect row_id in your cursor and convert it into a int value then show it on screen.
Done.

Deleting database items in a ListView (created from an ArrayAdapter)

I have created a database which is displayed in a ListView using an ArrayAdapter. I want a selected ListView item to be deleted when a ContextMenu pops up with a delete option as depicted below:
I have a class for handling all the database functions like delete. When I use a normal onCLicklistener with a button, the delete function is performed correctly, i.e it deletes the correct database entry and reaches the if (cursor.moveToFirst()) line. When I make use of the delete menu item, it does not reach the if (cursor.moveToFirst()) line in the attached delete handler function and therefore does not delete the entry (attached after the ListView code snippet below is the delete handler).
Any help/guidance/examples will be greatly appreciated.
My ListView is populated as follows:
public class Listview extends AppCompatActivity
{
private ListView users;
FloatingActionButton fab;
MyDBHandler dbHandler;
ArrayAdapter<String> arrayAdapter;
String lists;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.activity_listview);
// Create back button in action bar
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
users = (ListView) findViewById(R.id.clientlst);
// Floating Action bar for adding new data entries
fab = (FloatingActionButton) findViewById(R.id.fab1);
MyDBHandler dbHandler = new MyDBHandler(getApplicationContext());
lists = dbHandler.loadHandler();
//Create a list of the saved database String array items and split into
Strings
ArrayList<String> list = new ArrayList<>
(Arrays.asList(lists.split("\n")));
// Create the List view adapter
arrayAdapter = new ArrayAdapter<String>(Listview.this,
android.R.layout.simple_list_item_1, android.R.id.text1, list)
{
#Override // Edit the Text colour of the Listview items
public View getView(int position, View convertView, ViewGroup parent)
{
String Items = arrayAdapter.getItem(position);
String[] separated = Items.split(":");
String Name123 = separated[1]; // This will contain "Name"
TextView textView = (TextView) super.getView(position,
convertView, parent);
textView.setTextColor(Color.BLUE);
textView.setText(Name123);
return textView;
}
};
users.setAdapter(arrayAdapter);
registerForContextMenu(users);
// Create an action to be performed by each click of an item in the
users.setOnItemClickListener
(
new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View
view, int position, long id) {
String Items = arrayAdapter.getItem(position);
String[] separated = Items.split(":");
String ip = separated[5]; // This will contain "PORT address"
String port = separated[3]; // This will contain "IP number"
Toast.makeText(Listview.this, port + ip,
Toast.LENGTH_LONG).show();
} // onItemClick
} // OnItemClickListener View
); // OnItemClickListener
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
Toast.makeText(Listview.this, "Fab
Clicked", Toast.LENGTH_LONG).show();
}
}
);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Choose an option");
MenuInflater inflator = getMenuInflater();
inflator.inflate(R.menu.example_menu, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item)
{
AdapterView.AdapterContextMenuInfo info =
(AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId())
{
case R.id.option_1:
arrayAdapter.getItem(info.position);
MyDBHandler dbHandler = new MyDBHandler(getApplicationContext());
String Items= arrayAdapter.getItem(info.position);
String[] separated = Items.split(":");
String ip = separated[3]; // This will
contain "IP addr"
String names = separated[1]; // This will
contain "Name"
Log.d("LATE",names + ip);
dbHandler.deleteHandler(names,ip);
arrayAdapter.notifyDataSetChanged(); // Refresh the
listview
Toast.makeText(this, "Deleted", Toast.LENGTH_SHORT).show();
Intent listviews1 = new Intent(Listview.this, Listview.class);
startActivity(listviews1);
return true;
case R.id.option_2:
Intent listviews2 = new Intent(Listview.this, Listview.class);
startActivity(listviews2);
Toast.makeText(this, "Updated", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onContextItemSelected(item);
}
}
}
The delete handler function of the database is as follows:
public void deleteHandler(String username, String IP)
{
//boolean result = false;
String query = "Select*FROM " + TABLE_USER + " WHERE " + COLUMN_NAME + "
= '" + String.valueOf(username) + "'" + " and " + COLUMN_ID + " = '" +
String.valueOf(IP) + "'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
Log.d ("MEH", String.valueOf(cursor));
User user = new User();
if (cursor.moveToFirst())
{
user.setUserName(cursor.getString(2));
user.setID(cursor.getString(3));
db.delete(TABLE_USER, COLUMN_NAME + "=? and " + COLUMN_ID + "=?",
new String[]
{
String.valueOf(user.getUserName()),
String.valueOf(user.getID())
});
cursor.close();
//result = true;
}
db.close();
//return result;
}
You aren't calling any method to delete the item from the database from your users.setOnItemClickListener
As you added in your comment, all you are doing is trying to delete the item from your ActionBar's onItemClicked method.
Do the same inside your OnItemClickListener
Update2: Change in requirement
users.setLongClickable(true);
users.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) {
//Do your tasks here
AlertDialog.Builder alert = new AlertDialog.Builder(
YourActivity.this);
alert.setTitle("Alert!!");
alert.setMessage("Choose an option");
alert.setPositiveButton("Edit", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//do your work here
dialog.dismiss();
}
});
alert.setNegativeButton("Delete", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//perform your delete callback here
dialog.dismiss();
}
});
alert.show();
return true;
}
});
Update1: Explanation to Amiya's answer,
The reason why
cursor.moveToFirst() isn't a good option is because this statement
is unnecessary. The compiler knows exact spot to hit when it will
enter inside your DB. One usually perform cursor.moveToFirst()
when you need to iterate through all or some data elements from your
database.
"Make sure, COLUMN_ID is PRIMARY Key." Reason behind this is to avoid duplicity in case you ever add a functionality of adding items on the run time.
REMOVE this if (cursor.moveToFirst()) .
Make sure, COLUMN_ID is PRIMARY Key.
Check deleteHandler() method is invoking or not.
You should try with
public void deleteHandler(String username, String IP)
{
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_USER,
COLUMN_NAME + " = ? AND " + COLUMN_ID + " = ?",
new String[] {username, IP});
db.close();
}

Delete an item from ListView and database in Android

I have a listview that gets the data from an Arraylist and this Arraylist gets data from a database. Now I want to delete an item from the listview and also I want to delete this record from database. In addition, the delete option is in a contextmenu. I just want to know how to send the record's Id to the listview items and also the delete method in the dataModel. I can have the ID by reslist.getId()
Here is getView and contextmenu:
public View getView(int i, View view, ViewGroup viewGroup) {
View v = view;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.list_layout, null);
}
TextView tv1 = (TextView) v.findViewById(R.id.resName);
TextView tv2 = (TextView) v.findViewById(R.id.resAddress);
ImageView iv = (ImageView) v.findViewById(R.id.resType);
tv1.setText(resList.get(i).getName());
tv2.setText(resList.get(i).getAddress());
iv.setImageResource(R.drawable.tpng);
if(resList.get(i).getType().equals("takeaway")){
iv.setImageResource(R.drawable.tpng);
}else if(resList.get(i).getType().equals("delivery")){
iv.setImageResource(R.drawable.dpng);
}else if(resList.get(i).getType().equals("sitdown")){
iv.setImageResource(R.drawable.spng);
}
registerForContextMenu(v);
return v;
}
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
getMenuInflater().inflate(R.menu.list_menu, menu);
super.onCreateContextMenu(menu, v, menuInfo);
}
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.remove:
// I should use delete method here and I just want Item Id
break;
case R.id.item2:
break;
}
return super.onContextItemSelected(item);
}
and this is the delete method in dataModel
public void deleteRestaurant(int id){
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_RESTAURANT + "WHERE" + KEY_ID + " = ?", new String[] {String.valueOf(id)});
}
To delete a record from the sqlite database , you can use the following code :
public void deleteRestaurant(int id) {
System.out.println("the deleted restaurant has the id: " + id);
SQLiteDatabase db = getWritableDatabase();
db.delete(TABLE_RESTAURANT, KEY_ID + " = " + id, null);
}
Check this full tutorial about how to use SQLite Database with Multiple Tables in Android
If you use a CursorLoader with your Adapter, all you have to do is delete the row in the database and the rest will happen automatically.
Here is a link: Loaders
you need to get the position of the selected item. then remove item from your Array list. Once you have removed the item, call the notifyDataSetChanged method then it will automatically remove the view.
switch(item.getItemId()){
case R.id.remove:
// I should use delete method here and I just want Item Id
deleteRestaurant(id);
arrayList.remove(position);
notifyDataSetChanged();
break;
case R.id.item2:
break;

Retrieve _id value without context menu

I am building a custom ListView (card style) and would like to have an edit and delete button on the card. In order to invoke the methods on the correct database rows, I need to know which _id (View) the user selected.
Currently, I am using a context menu which is pretty easy
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
position = (int) info.id;
MenuInflater m = getMenuInflater();
m.inflate(R.menu.history_popup_menu, menu);
}
#Override
public boolean onContextItemSelected(final MenuItem item) {
switch(item.getItemId()){
case R.id.delete:
...
in this case, I get the id (position) in the onCreateContextMenu
I am wanting to get rid of the context menu now and just have edit and delete on the card itself.
How do I go about retrieving the _id from the database and assign it to a value to be used in my delete/edit method?
This is my method for creating the list
private void addItemsToList(){
Cursor cursor = db.getAllLogs();
Log.d("history.java", "finished Cursor cursor = db.getAllLogs();");
String[] from = {"_id", "date", "gallons", "pricePerGallon", "odometer", "filledOrNot", "comments", "totalSpent"};
int[] to = {deleteVal, R.id.cardDate, R.id.cardGallons, R.id.cardPrice, R.id.cardOdometer, R.id.cardFilledOrNot, R.id.cardComments, R.id.usd};
adapter = new SimpleCursorAdapter(this, R.layout.history_list_item, cursor, from, to, 0);
String filledOrNotVal = String.valueOf(R.id.cardFilledOrNot);
if (filledOrNotVal == "False"){
Log.d("history", "False");
} else {
Log.d("history", "True");
}
listContent.setAdapter(adapter);
}

Detecting which selected item (in a ListView) spawned the ContextMenu (Android)

I have a ListView that will allow the user to long-press an item to get a context menu. The problem I'm having is in determining which ListItem they long-pressed. I've tried doing this:
myListView.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
#Override public void onCreateContextMenu(ContextMenu menu, final View v, ContextMenuInfo menuInfo) {
menu.add("Make Toast")
.setOnMenuItemClickListener(new OnMenuItemClickListener() {
#Override public boolean onMenuItemClick(MenuItem item) {
String toastText = "You clicked position " + ((ListView)v).getSelectedItemPosition();
Toast.makeText(DisplayScheduleActivity.this, toastText, Toast.LENGTH_SHORT).show();
return true;
}
});
}
});
but it just hangs until an ANR pops up. I suspect that after the menu is created the ListItem is no longer selected.
It looks like you could monitor for clicks or long-clicks then record the clicked item there:
mArrivalsList.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) {
// record position/id/whatever here
return false;
}
});
but that feels majorly kludgey to me. Does anyone have any better solutions for this?
I do exactly this. In my onCreateContextMenu(...) method, I cast the ContextMenu.ContextMenuInfo to AdapterView.AdapterContextMenuInfo. From there, you can get the targetView, which you cast again to the widget. The complete code is available in HomeActivity.java, look for the onCreateContextMenu(...) method.
#Override
public void onCreateContextMenu(ContextMenu contextMenu,
View v,
ContextMenu.ContextMenuInfo menuInfo) {
AdapterView.AdapterContextMenuInfo info =
(AdapterView.AdapterContextMenuInfo) menuInfo;
selectedWord = ((TextView) info.targetView).getText().toString();
selectedWordId = info.id;
contextMenu.setHeaderTitle(selectedWord);
contextMenu.add(0, CONTEXT_MENU_EDIT_ITEM, 0, R.string.edit);
contextMenu.add(0, CONTEXT_MENU_DELETE_ITEM, 1, R.string.delete);
}
Note that I store the selected text as well as the select id in private fields. Since the UI is thread confined, I know the selectedWord and selectedWordId fields will be correct for later actions.
First of all, I'm wondering if you're making things a little overly complicated by using View.setOnCreateContextMenuListener(). Things get a lot easier if you use Activity.registerForContextMenu(), because then you can just use Activity.onCreateContextMenu() and Activity.onContextItemSelected() to handle all of your menu events. It basically means you don't have to define all these anonymous inner classes to handle every event; you just need to override a few Activity methods to handle these context menu events.
Second, there's definitely easier ways to retrieve the currently selected item. All you need to do is keep a reference either to the ListView or to the Adapter used to populate it. You can use the ContextMenuInfo as an AdapterContextMenuInfo to get the position of the item; and then you can either use ListView.getItemAtPosition() or Adapter.getItem() to retrieve the Object specifically linked to what was clicked. For example, supposing I'm using Activity.onCreateContextMenu(), I could do this:
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
// Get the info on which item was selected
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
// Get the Adapter behind your ListView (this assumes you're using
// a ListActivity; if you're not, you'll have to store the Adapter yourself
// in some way that can be accessed here.)
Adapter adapter = getListAdapter();
// Retrieve the item that was clicked on
Object item = adapter.getItem(info.position);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
// Here's how you can get the correct item in onContextItemSelected()
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
Object item = getListAdapter().getItem(info.position);
}
this is another way on how to create context menu n how to delete the item selected here is the whole code
public class SimpleJokeList extends Activity {
public static final int Upload = Menu.FIRST + 1;
public static final int Delete = Menu.FIRST + 2;
int position;
ListView lv;
EditText jokeBox;
Button addJoke;
MyAdapter adapter;
private ArrayAdapter<String> mAdapter;
private ArrayList<String> mStrings = new ArrayList<String>();
String jokesToBeAdded;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simplejokeui);
lv=(ListView)findViewById(R.id.jokelist);
addJoke=(Button)findViewById(R.id.addjoke);
jokeBox=(EditText)findViewById(R.id.jokebox);
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mStrings);
registerForContextMenu(lv);
listItemClicked();
addJokes();
private void addJokes() {
// TODO Auto-generated method stub
addJoke.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
jokesToBeAdded=jokeBox.getText().toString();
if(jokesToBeAdded.equals("")){
Toast.makeText(getApplicationContext(), "please enter some joke", Toast.LENGTH_LONG).show();
}
else{
lv.setAdapter(mAdapter);
mAdapter.add(jokesToBeAdded);
jokeBox.setText(null);
}
}
});
}
private void listItemClicked() {
// TODO Auto-generated method stub
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
position=arg2;
return false;
}
});
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
super.onCreateContextMenu(menu, v, menuInfo);
populateMenu(menu);
menu.setHeaderTitle("Select what you wanna do");
}
private void populateMenu(ContextMenu menu) {
// TODO Auto-generated method stub
menu.add(Menu.NONE, Upload, Menu.NONE, "UPLOAD");
menu.add(Menu.NONE, Delete, Menu.NONE, "DELETE");
}
#Override
public boolean onContextItemSelected(MenuItem item)
{
return (applyMenuChoice(item) || super.onContextItemSelected(item));
}
private boolean applyMenuChoice(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId())
{
case Delete:
String s=mAdapter.getItem(position);
mAdapter.remove(s);
// position--;
Toast.makeText(getApplicationContext(),"Congrats u HAve Deleted IT", Toast.LENGTH_LONG).show();
return (true);
}
return false;
}
And don't forget to put this
registerForContextMenu(listview);
in your onCreate method to get your context Menu visible.
We have used with success:
#Override
public boolean onContextItemSelected
(
MenuItem item
)
{
if (!AdapterView.AdapterContextMenuInfo.class.isInstance (item.getMenuInfo ()))
return false;
AdapterView.AdapterContextMenuInfo cmi =
(AdapterView.AdapterContextMenuInfo) item.getMenuInfo ();
Object o = getListView ().getItemAtPosition (cmi.position);
return true;
}
Isn't the view argument the actual selected row's view, or am I missing the question here?
ListView lv;
private OnItemLongClickListener onLongClick = new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
lv.showContextMenuForChild(arg1);
lv.showContextMenu();
return false;
}
};
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
View TargetV=(View) info.targetView;
text1 = (String) ((TextView) TargetV.findViewById(R.id.textView1)).getText();
text2 = (String) ((TextView) TargetV.findViewById(R.id.textView2)).getText();
if(List3Ok){
text3 = (String) ((TextView) TargetV.findViewById(R.id.textView3)).getText();
}
selectedWord = text1 + "\n" + text2 + "\n" + text3;
selectedWordId = info.id;
menu.setHeaderTitle(selectedWord);
MenuInflater inflater = this.getActivity().getMenuInflater();
inflater.inflate(R.menu.list_menu, menu);
}
I case you are using SimpleCursorAdapder you may do it like this
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
getActivity().getMenuInflater().inflate(R.menu.project_list_item_context, menu);
// Getting long-pressed item position
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
int position = info.position;
// Get all records from adapter
Cursor c = ((SimpleCursorAdapter)getListAdapter()).getCursor();
// Go to required position
c.moveToPosition(position);
// Read database fields values associated with our long-pressed item
Log.d(TAG, "Long-pressed-item with position: " + c.getPosition());
Log.d(TAG, "Long-pressed-item _id: " + c.getString(0));
Log.d(TAG, "Long-pressed-item Name: " + c.getString(1));
Log.d(TAG, "Long-pressed-item Date: " + c.getString(2));
Log.d(TAG, "Long-pressed-item Path: " + c.getString(3));
// Do whatever you need here with received values
}

Categories

Resources