Reputation: 5431
I made a listview where at the header an edit text field to add list.And it works fine and successfully add item. Then I try to call this listview and set the adapter. Now what I want is when I click the item it should be deleted, but its getting force closed. Here is my code:
public class AddDeleteItemActivity extends ListActivity {
public ListView listViewCity;
public Context ctx;
ArrayList list = new ArrayList();
ArrayAdapter adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn = (Button) findViewById(R.id.btnAdd);
ctx=this;
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_multiple_choice, list);
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();
}
};
listViewCity = ( ListView ) findViewById( R.id.list);
listViewCity.setAdapter(adapter);
listViewCity.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Toast.makeText(getApplicationContext(), " " +position , Toast.LENGTH_LONG).show();
SparseBooleanArray checkedItemPositions = getListView().getCheckedItemPositions();
int itemCount = getListView().getCount();
for(int i=itemCount-1; i >= 0; i--){
if(checkedItemPositions.get(i)){
adapter.remove(list.get(i));
}
}
adapter.notifyDataSetChanged();
}
});
btn.setOnClickListener(listener);
setListAdapter(adapter);
}
}
Upvotes: 4
Views: 4825
Reputation: 30855
try this way
listViewCity.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Toast.makeText(getApplicationContext(), " " +position , Toast.LENGTH_LONG).show();
list.remove(position);
adapter.notifyDataSetChanged();
adapter.notifyDataSetInvalidated();
}
});
remove from the list and refresh your list using adapter notification
edited
why you are used this statement when you extend the ListActivity
listViewCity = ( ListView ) findViewById( R.id.list);
either you can get the ListView object using getListView() with extending the ListActivity or extends the Activity instead of ListActivity.
Upvotes: 5