Delete List Items in different tabs - android

I have a tab host activity using two separate databases. Each tab has a list view. I am trying to use a context menu to delete a list item with a long click. What I have will work on list1 tab, but will not delete the list item in the list2 tab. Here is my code:
public class TabListActivity extends TabActivity implementsOnTabChangeListener,OnClickListener{
private static final String LIST1_TAB_TAG = "Mixed Recipes";
private static final String LIST2_TAB_TAG = "Pre-Mixed Recipes";
// The two views in our tabbed example
private ListView listView1;
private ListView listView2;
private TabHost tabHost;
private DatabaseManager mDbHelper;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabs);
mDbHelper = new DatabaseManager(this);
mDbHelper.open();
tabHost = getTabHost();
tabHost.setOnTabChangedListener(this);
// setup list view 1
listView1 = (ListView) findViewById(R.id.list1);
registerForContextMenu(listView1);
// setup list view 2
listView2 = (ListView) findViewById(R.id.list2);
registerForContextMenu(listView2);
// add views to tab host
tabHost.addTab(tabHost.newTabSpec(LIST1_TAB_TAG).setIndicator(LIST1_TAB_TAG).setContent(new TabContentFactory() {
public View createTabContent(String arg0) {
return listView1;
}
}));
tabHost.addTab(tabHost.newTabSpec(LIST2_TAB_TAG).setIndicator(LIST2_TAB_TAG).setContent(new TabContentFactory() {
public View createTabContent(String arg0) {
return listView2;
}
}));
tabHost.setCurrentTab(1);
tabHost.setCurrentTab(0);
}
/**
* Implement logic here when a tab is selected
*/
public void onTabChanged(String tabName) {
if(tabName.equals(LIST2_TAB_TAG)) {
//do something
fillDatapremix();
}
else if(tabName.equals(LIST1_TAB_TAG)) {
//do something
fillData();
}
}
private void fillData() {
Cursor notesCursor = mDbHelper.fetchAllNotes();
startManagingCursor(notesCursor);
// Create an array to specify the fields we want to display in the list (only TITLE)
String[] from = new String[]{DatabaseManager.KEY_NAME, DatabaseManager.KEY_ROWID};
//String1[] from = new String[]{DatabaseManager.KEY_ROWID};
// and an array of the fields we want to bind those fields to (in this case just text1)
int[] to = new int[]{android.R.id.text1};
//int[] to = new int[]{android.R.id.text2};
// Now create a simple cursor adapter and set it to display
SimpleCursorAdapter notes =
new SimpleCursorAdapter(this,android.R.layout.simple_list_item_2, notesCursor, from, to);
listView1.setAdapter(notes);
listView1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent myIntent = new Intent(view.getContext(),
NoCalc.class);
myIntent.putExtra(DatabaseManager.KEY_ROWID, id);
startActivity(myIntent);
}
});
}
public void onClick(View v) {
// TODO Auto-generated method stub
}
private void fillDatapremix() {
Cursor notesCursor = mDbHelper.fetchAllNotespremix();
startManagingCursor(notesCursor);
// Create an array to specify the fields we want to display in the list (only TITLE)
String[] from = new String[]{DatabaseManager.KEY_NAME, DatabaseManager.KEY_ROWID};
//String1[] from = new String[]{DatabaseManager.KEY_ROWID};
// and an array of the fields we want to bind those fields to (in this case just text1)
int[] to = new int[]{android.R.id.text1};
//int[] to = new int[]{android.R.id.text2};
// Now create a simple cursor adapter and set it to display
SimpleCursorAdapter notes =
new SimpleCursorAdapter(this,android.R.layout.simple_list_item_2, notesCursor, from, to);
listView2.setAdapter(notes);
listView2.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent myIntent = new Intent(view.getContext(),
Premix2.class);
myIntent.putExtra(DatabaseManager.KEY_ROWID, id);
startActivity(myIntent);
}
});
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
switch (v.getId()) {
}
menu.setHeaderTitle("Delete Recipe?");
menu.add(0, v.getId(), 0, "Delete");
}
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.list1:
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
mDbHelper.deleteRow(info.id);
fillData();
return true;
case R.id.list2:
AdapterContextMenuInfo info1 = (AdapterContextMenuInfo) item.getMenuInfo();
mDbHelper.deleteRow(info1.id);
fillData();
return true;
}
return false;
}
}
My question is, how do I get the second tab to delete the list item from the list and the database?

You have separate fillData() and fillDatapremix() functions and 2 separate functions to retrieve cursors from your 2 databases, but it looks like in your onContextItemSelected function you are using the same DatabaseManger delete function and fillData() function for each list.
Looks like you need to use a different delete function for your second database and then use fillDatapremix() to update the listView rather than fillData().

Related

Display a Snackbar in a fragment after deleting an item from the database?

I am looking for a way to have a Snackbox pop up at the bottom of the display when the user deletes an item from the database using the caseR.id.delete:. Below I have attached code from the fragment. If you need more of my code from different areas, please let me know.
/**
* A simple {#link Fragment} subclass.
*/
public class MainActivityListFragment extends ListFragment {
private ArrayList<Note> notes;
private NoteAdapter noteAdapter;
#Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
/*
String[] values = new String[] {"Android", "iPhone", "Windows", "WebOS", "Android", "iPhone", "Windows", "WebOS" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
*/
NotesDbAdapter dbAdapter = new NotesDbAdapter(getActivity().getBaseContext());
dbAdapter.open();
notes = dbAdapter.getAllNotes();
dbAdapter.close();
noteAdapter = new NoteAdapter(getActivity(), notes);
setListAdapter(noteAdapter);
getListView().setDivider(null);
getListView().setDividerHeight(0);
registerForContextMenu(getListView());
}
#Override
public void onListItemClick(ListView l, View v, int position, long id){
super.onListItemClick(l, v, position, id);
launchNoteDetailActivity(MainActivity.FragmentToLaunch.VIEW, position);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo){
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater menuInflater = getActivity().getMenuInflater();
menuInflater.inflate(R.menu.long_press_menu, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item){
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
int rowPosition = info.position;
Note note = (Note) getListAdapter().getItem(rowPosition);
switch (item.getItemId()){
case R.id.edit:
launchNoteDetailActivity(MainActivity.FragmentToLaunch.EDIT, rowPosition);
Log.d("menu clicks", "we pressed edit");
return true;
case R.id.delete:
NotesDbAdapter dbAdapter = new NotesDbAdapter(getActivity().getBaseContext());
dbAdapter.open();
dbAdapter.deleteNote(note.getId());
notes.clear();
notes.addAll(dbAdapter.getAllNotes());
noteAdapter.notifyDataSetChanged();
dbAdapter.close();
}
return super.onContextItemSelected(item);
}
private void launchNoteDetailActivity(MainActivity.FragmentToLaunch ftl, int position){
Note note = (Note) getListAdapter().getItem(position);
Intent intent = new Intent(getActivity(), NoteDetailActivity.class);
intent.putExtra(MainActivity.NOTE_TITLE_EXTRA, note.getTitle());
intent.putExtra(MainActivity.NOTE_MESSAGE_EXTRA, note.getMessage());
intent.putExtra(MainActivity.NOTE_CATEGORY_EXTRA, note.getCategory());
intent.putExtra(MainActivity.NOTE_DATE_EXTRA, note.getDate());
intent.putExtra(MainActivity.NOTE_ID_EXTRA, note.getId());
switch(ftl){
case VIEW:
intent.putExtra(MainActivity.NOTE_FRAGMENT_TO_LOAD_EXTRA, MainActivity.FragmentToLaunch.VIEW);
break;
case EDIT:
intent.putExtra(MainActivity.NOTE_FRAGMENT_TO_LOAD_EXTRA, MainActivity.FragmentToLaunch.EDIT);
}
startActivity(intent);
}
}
In your build.gradle add latest design library.
compile 'com.android.support:design:X.X.X' // where X.X.X version
And then, in your fragment do:
Snackbar
.make(view, "Item deleted",Snackbar.LENGTH_SHORT)
.show();
The parameter view could be the fragment's root layout. You just need it's reference.
For more information see http://www.materialdoc.com/snackbar/
Add design Lib
Compile 'com.android.support:design:X.X.X'
Code:
case R.id.delete:
NotesDbAdapter dbAdapter = new NotesDbAdapter(getActivity().getBaseContext());
dbAdapter.open();
dbAdapter.deleteNote(note.getId());
notes.clear();
notes.addAll(dbAdapter.getAllNotes());
noteAdapter.notifyDataSetChanged();
dbAdapter.close();
// Show SNACK Bar
mRoot = (RelativeLayout) view.findViewById(R.id.mainrl);
Snackbar snackbar = Snackbar.make(mRoot , "Item Deleted", Snackbar.LENGTH_LONG);
snackbar.show();
here mRoot is your main root layout of your fragment.

onContextItemSelected not called using a Dialog with a ListView

I'm creating a simple dialog with a ListView on it. I want to be able to access a context menu on it. Here's the basic code I've:
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.activity_lista);
dialog.setTitle("Contact");
ListView lv = (ListView) dialog.findViewById(R.id.listView); Cursor cursor = db.readData();
String[] from = new String[]{DatabaseHandler.KEY_contacts, DatabaseHandler.KEY_number};
int[] to = new int[]{R.id.contacts, R.id.number};
#SuppressWarnings("deprecation")
final
SimpleCursorAdapter adapter = new SimpleCursorAdapter(Home.this, R.layout.show, cursor, from, to);
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
registerForContextMenu(lv);
here the method onCreateContextMenu:
#Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
getMenuInflater().inflate(R.menu.menu_context, menu);
}
And finally I override the onContextItemSelected:
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.call:
Toast.makeText(this,"call" ,Toast.LENGTH_LONG).show();
return true;
case R.id.sms:
Toast.makeText(this,"sms" ,Toast.LENGTH_LONG).show();
return true;
case R.id.delete:
Toast.makeText(this,"delete" ,Toast.LENGTH_LONG).show();
return true;
default:
return super.onContextItemSelected(item);
}
}
I've tried also to override setOnMenuItemClickListener() inside onContextItemSelected()
but my problem still is not solved :( Any help?
You can get Item using this method
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Object listItem = lv.getItemAtPosition(position);
}
});

How to delete a row from a ListView with a CursorAdapter

I started a small Android project to re-learn a bit of Android development, and I'm already stuck...
I do not know how to implement the deletetion of an element of my ListView!
Here is the project: https://github.com/gdurelle/Listify
Right now it aims at showing a list of lists of elements.
I use a custom CursorAdapter to show my list of elements, and I already have a (ugly) destroy button, but I do not know how to make it delete an actual element from the list (and the database).
I use ActiveAndroid to manage the database in the ActiveRecord way.
Plus: I'm not sure wether or not to use getView(), bindView(), and/or newView()...
I created an issue to remember this and reference this question here: https://github.com/gdurelle/Listify/issues/1
public class ListifyCursorAdapter extends CursorAdapter {
public String content;
public ListifyCursorAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
}
// The newView method is used to inflate a new view and return it, you don't bind any data to the view at this point.
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.element_line, parent, false);
}
// The bindView method is used to bind all data to a given view such as setting the text on a TextView.
#Override
public void bindView(View view, Context context, Cursor cursor) {
// Find fields to populate in inflated template
TextView tvBody = (TextView) view.findViewById(R.id.element_content);
// Extract properties from cursor
content = cursor.getString(cursor.getColumnIndexOrThrow("content"));
// Populate fields with extracted properties
tvBody.setText(content);
}
}
And in my MainActivity :
Cursor cursor = ListifyElement.fetchResultCursor();
adapter = new ListifyCursorAdapter(this, cursor);
listView.setAdapter(adapter);
I was thinking maybe about a:
Button delete_button = (Button) listView.findViewById(R.id.delete_button);
with something like ListifyElement.load(ListifyElement.class, the_id_of_the_element).delete(); where the_id_of_the_element would be the DB's id of the element retrieived somehow from the click on it's delete_button in the UI...
UPDATE:
#Override
public void bindView(View view, Context context, final Cursor cursor) {
// Find fields to populate in inflated template
TextView tvBody = (TextView) view.findViewById(R.id.element_content);
// Extract properties from cursor
content = cursor.getString(cursor.getColumnIndexOrThrow("content"));
// Populate fields with extracted properties
tvBody.setText(content);
Button delete_button = (Button) view.findViewById(R.id.delete_button);
delete_button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
System.out.println(cursor.getColumnName(0)); // Id
System.out.println(cursor.getColumnName(1)); // ListifyContainer
System.out.println(cursor.getColumnName(2)); // content
System.out.println(cursor.getColumnIndexOrThrow("Id")); // 0
ListifyElement.load(ListifyElement.class, cursor.getColumnIndexOrThrow("Id")).delete();
notifyDataSetChanged();
}
});
I get this error when I click the delete button:
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.gdurelle.listify.models.ListifyElement.delete()' on a null object reference
If you want a Button in each row, you should add it to your xml which you inflate in the newView(). After that, you should set OnClickListener to your Button inside bindView(). Something like that:
public void bindView(View view, Context context, Cursor cursor) {
// Find fields to populate in inflated template
TextView tvBody = (TextView) view.findViewById(R.id.element_content);
Button delete_button = (Button) view.findViewById(R.id.delete_button);
delete_button.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
//As you're using ActiveAndroid
new Delete().from(ListfyElement.class).where("yourCondition=?",yourCondition).execute();
notifyDataSetChanged();
}
});
// Extract properties from cursor
content = cursor.getString(cursor.getColumnIndexOrThrow("content"));
// Populate fields with extracted properties
tvBody.setText(content);
}
Use below code to perform this--
ListView lv;
ArrayList<String> arr = new ArrayList<String>();
ArrayAdapter adapter;
int position;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.extra);
for(int i=0;i<5;i++)arr.add("Hi # "+i);
lv = (ListView) findViewById(R.id.listViewBirthday);
lv.setOnItemLongClickListener(this);
adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, arr);
lv.setAdapter(adapter);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
super.onCreateContextMenu(menu, v, menuInfo);
MenuItem it1=menu.add("Delete");
}
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int p, long arg3)
{
position = p;
registerForContextMenu(lv);
return false;
}
#Override
public boolean onContextItemSelected(MenuItem item) {
// TODO Auto-generated method stub
if(item.getTitle().equals("Delete"))
{
arr.remove(position);
adapter.notifyDataSetChanged();
Toast.makeText(getBaseContext(), "deleted", Toast.LENGTH_SHORT).show();
}
return true;
}
The context menu is relatively simple to implement on a listview. It (context menu) is activated on a long press of the item. My tip is to add an intent to the menu item so you can preserve the item id from your custom adapter and use it to perform whatever you want.
public class MainActionBarTabListFragment extends ListFragment {
#Override
public void onActivityCreated(Bundle savedState) {
super.onActivityCreated(savedState);
registerForContextMenu(getListView());
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
String name = adapter2.getItem(info.position).get_name();
menu.setHeaderTitle(name);
MenuInflater inflater = this.getActivity().getMenuInflater();
inflater.inflate(R.menu.menulistitem, menu);
MenuItem mi = menu.findItem(R.id.action_context_delete);
Intent i = new Intent();
i.putExtra("id", adapter2.getItem(info.position).get_id());
mi.setIntent(i);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_context_delete:
Intent i = item.getIntent();
if (i != null) {
Bundle b = i.getExtras();
if (b != null) {
int id = b.getInt("id");
Uri deleteIdUri = ContentUris.withAppendedId(
RidesDatabaseProvider.CONTENT_URI, id);
context.getContentResolver()
.delete(deleteIdUri, null, null);
return true;
}
}
}
return super.onContextItemSelected(item);
}
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:yourapp="http://schemas.android.com/apk/res-auto" >
<item
android:id="#+id/action_context_delete"
android:icon="#drawable/action_about"
android:orderInCategory="100"
android:showAsAction="ifRoom"
android:title="delete"
yourapp:showAsAction="ifRoom"/>
</menu>
lets start from the beginning, why do you need to use ActiveAndroid? I suggest to avoid such things, IMHO. You've mixed your logic, adapter should not change your database. Set a listener to adapter (i.e. IDeleteListener with single method onDeleteRequested(long rowId)). Next you need to pass rowId, something like:
delete_button.setTag(cursor.getLong(0));
delete_button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
listener.onDeleteRequested((Long)v.getTag());
}
});
In your fragment/activity class you should set a listener to adapter and work with your database. I suggest you to use LoaderManager this will automatically re-query your db on delete and handle life cycle of activity.
Hope that helps!
I would suggest you to use an ArrayAdapter instead. Then you are just using an ArrayList (or any other array) and edit it, and call adapter.notifyDataSetChanged();, and the content of the ListView will update.
Declare the ArrayAdapter like this:
ArrayAdapter<String> adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, yourStringArray);
where the variable called yourStringArray is just an ArrayListof Strings.
Then, add the adapter to the ListView, like this:
yourListView.setAdapter(adapter);
Then, you can modify the contents of the list, by editing the yourStringArray list, and calling adapter.notifyDataSetChanged();. Here is a simple example:
list.add("Hello!");
adapter.notifyDataSetChanged();
Finally, to remove the selected item when the button is clicked, you can do something like this:
int selectedItemIndex = 0;
yourArrayList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectedItemIndex = position;
}
});
yourDestroyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
yourStringArray.remove(selectedItemIndex);
adapter.notifyDataSetChanged();
}
});
The whole onCreate method would look something like this:
// Called when the activity is created
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<String> yourStringArray = new ArrayList<>();
ArrayAdapter<String> adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, yourStringArray);
int selectedItemIndex = 0;
ListView yourListView = (ListView) findViewById(R.layout.yourListViewID);
yourListView.setAdapter(adapter);
yourListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectedItemIndex = position;
}
});
yourDestroyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
yourStringArray.remove(selectedItemIndex);
adapter.notifyDataSetChanged();
}
});
}

Making a custom android ListView adapter Clickable

I've been trying to create a clickable listview that takes in a string array and a few images and presents them in a textview style. So far I have managed to create a listview with each of the strings and images, however I am unsure how to use the onClick method so as to make the textviews clickable to start new activities etc.
Here is my code so far (Excluding XML):
public class MySimpleArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
public MySimpleArrayAdapter(Context context, String[] values) {
super(context, R.layout.activity_test2, values);
this.context = context;
this.values = values;
}
/* Print a toast when a list item is clicked, don't know what to do */
public void onClick() {
switch (list item) {
case 0:
Toast.makeText(this.context, "Pressed!", Toast.LENGTH_LONG).show()
break;
}
case 1:
etc....
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.activity_test2, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.label);
ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
textView.setText(values[position]);
String s = values[position];
if (s.startsWith("Report a Road Delay")) {
imageView.setImageResource(R.drawable.ic_menu_compose);
} else if (s.startsWith("View Reported Delays")) {
imageView.setImageResource(R.drawable.ic_menu_view);
} else if (s.startsWith("Search a Road for Delays")) {
imageView.setImageResource(R.drawable.ic_menu_search);
} else if (s.startsWith("Update a Delay Report")) {
imageView.setImageResource(R.drawable.ic_menu_edit);
} else if (s.startsWith("Validate a Delay Report")) {
imageView.setImageResource(R.drawable.ic_menu_mark);
}
return rowView;
}
}
public class MainActivity extends ListActivity {
public void onCreate(Bundle SavedInstanceState) {
super.onCreate(SavedInstanceState);
String[] values = new String[] { "Report a Road Delay",
"View Reported Delays", "Search a Road for Delays",
"Update a Delay Report", "Validate a Delay Report" };
MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(this, values);
setListAdapter(adapter);
}
}
This is how it looks so far:
All I basically don't understand is the onClick method; what parameters it takes it, and how to determine which item was clicked. Any help would be appreciated.
Try this:
ListView list1 = getListView();
list1.setOnItemClickListener(
new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View view,
int position, long id) {
//Take action here.
}
}
);
You are looking for an OnItemClickListener and not an OnClickListener
lv.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// DO SOMETHING WITH CICK EVENT HERE
}
}
Now only to discus the params:
parent The AdapterView where the click happened.
view The view within the AdapterView that was clicked
position The position of the view in the adapter.
id The row id of the item that was clicked.
I got the last part from android reference
You could use this code:
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parentAdapter, View view, int position,
long id) {
// We know the View is a <extView so we can cast it
TextView clickedView = (TextView) view;
Toast.makeText(MainActivity.this, "Item with id ["+id+"] - Position ["+position+"] - Planet ["+clickedView.getText()+"]", Toast.LENGTH_SHORT).show();
}
});
// we register for the contextmneu
registerForContextMenu(lv);
}
where lv is the listView.
If you want to add a context menu:
// We want to create a context Menu when the user long click on an item
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterContextMenuInfo aInfo = (AdapterContextMenuInfo) menuInfo;
// We know that each row in the adapter is a Map
Planet planet = aAdpt.getItem(aInfo.position);
menu.setHeaderTitle("Options for " + planet.getName());
menu.add(1, 1, 1, "Details");
menu.add(1, 2, 2, "Delete");
}
// This method is called when user selects an Item in the Context menu
#Override
public boolean onContextItemSelected(MenuItem item) {
int itemId = item.getItemId();
AdapterContextMenuInfo aInfo = (AdapterContextMenuInfo) item.getMenuInfo();
planetsList.remove(aInfo.position);
aAdpt.notifyDataSetChanged();
return true;
}
If you want to have more information give a look on my blog here and here

Getting listview item index in android

I am making an android application that uses a listview. I want to get the index number of an item once an item has been pressed(single-click). I've gone through several tutorials, but none seemed to help. How can i get the index number and pass it to a String. I do then want to delete it, but i'll manage that part my self. I only need the index number and pass it to a string. The code where i'll get the index number is straigt after the onCreate method. Please help and thanks in advance! This is the code that i am using:
public class NotesActivity extends ListActivity implements OnClickListener {
/** Called when the activity is first created. */
List<String> myList = new ArrayList<String>();
EditText AddItemToListViewEditText;
Button AddItemToListView, AddItemToListViewButton, CancelButton, DeleteButton;
LinearLayout AddItemToListViewLinearLayout, DeleteItemFromListViewLinearLayout;
public String DeleteIndexNumber;
static final String[] COUNTRIES = new String[] {
"Matte på A1 med Ole", "Engelsk på klasserommet", "Film på A1 etter friminuttet"
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notes);
setListAdapter((ListAdapter) new ArrayAdapter<String>(this, R.layout.list_item, COUNTRIES));
setListAdapter((ListAdapter) new ArrayAdapter<String>(this, R.layout.list_item, myList));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), "Note: " + ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
//This is where i need the index number to be passed to the string "DeleteIndexNumber"
DeleteItemFromListViewLinearLayout = (LinearLayout)findViewById(R.id.DeleteItemFromListViewLinearLayout);
DeleteItemFromListViewLinearLayout.setVisibility(View.VISIBLE);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu meny) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.listviewmenubuttons, meny);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.AddItemToListView:
AddItemToListViewButton = (Button)findViewById(R.id.AddItemToListViewButton);
CancelButton = (Button)findViewById(R.id.CancelButton);
DeleteButton = (Button)findViewById(R.id.DeleteButton);
CancelButton.setOnClickListener(this);
DeleteButton.setOnClickListener(this);
AddItemToListViewLinearLayout = (LinearLayout)findViewById(R.id.AddItemToListViewLinearLayout);
AddItemToListViewButton.setOnClickListener(this);
AddItemToListViewLinearLayout.setVisibility(View.VISIBLE);
break;
}
return true;
}
public void onClick(View src) {
switch(src.getId()) {
case R.id.AddItemToListViewButton:
AddItemToListViewEditText = (EditText)findViewById(R.id.AddItemToListViewEditText);
myList.add(AddItemToListViewEditText.getText().toString());
((ArrayAdapter)getListView().getAdapter()).notifyDataSetChanged();
AddItemToListViewEditText.setText("");
AddItemToListViewEditText.clearFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput (InputMethodManager.SHOW_FORCED, InputMethodManager.RESULT_HIDDEN);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
AddItemToListViewLinearLayout.setVisibility(View.GONE);
break;
case R.id.CancelButton:
DeleteItemFromListViewLinearLayout = (LinearLayout)findViewById(R.id.DeleteItemFromListViewLinearLayout);
DeleteItemFromListViewLinearLayout.setVisibility(View.INVISIBLE);
break;
case R.id.DeleteButton:
break;
}
}
}
notice the parameters for the onItemClick method
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
position will give you the index you desire..
Isn't it position parameter in onItemClick ?
The position parameter in onItemClick will give you the index of the clicked Item in the list.

Categories

Resources