Remove ListView items in Android - android

Can somebody please give me an example code of removing all ListView items and replacing with new items?
I tried replacing the adapter items without success. My code is
populateList(){
results //populated arraylist with strings
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, results);
listview.setAdapter(adapter);
adapter.notifyDataSetChanged();
listview.setOnItemClickListener(this);
}
// now populating list again
repopulateList(){
results1 //populated arraylist with strings
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, results1);
listview.setAdapter(adapter1);
adapter1.notifyDataSetChanged();
listview.setOnItemClickListener(this);
}
Here repopulateList() method will add to ListView items, but it doesn't remove/replace all ListView items.

You will want to remove() the item from your adapter object and then just run the notifyDatasetChanged() on the Adapter, any ListViews will (should) recycle and update on it's own.
Here's a brief activity example with AlertDialogs:
adapter = new MyListAdapter(this);
lv = (ListView) findViewById(android.R.id.list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
AlertDialog.Builder adb=new AlertDialog.Builder(MyActivity.this);
adb.setTitle("Delete?");
adb.setMessage("Are you sure you want to delete " + position);
final int positionToRemove = position;
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
MyDataObject.remove(positionToRemove);
adapter.notifyDataSetChanged();
}});
adb.show();
}
});

I think if u add the following code, it will work
listview.invalidateViews();
To remove an item, Just remove that item from the arraylist that we passed to the adapter and do listview.invalidateViews();
This will refresh the listview

You can use
adapter.clear()
that will remove all item of your first adapter then you could either set another adapter or reuse the adapter and add the items to the old adapter. If you use
adapter.add()
to add data to your list you don't need to call notifyDataSetChanged

int count = adapter.getCount();
for (int i = 0; i < count; i++) {
adapter.remove(adapter.getItem(i));
}
then call notifyDataSetChanged();

Remove it from the adapter and then notify the arrayadapter that data set has changed.
m_adapter.remove(o);
m_adapter.notifyDataSetChanged();

names = db.getSites();
la = new ArrayAdapter<String>(EditSiteList.this,
android.R.layout.simple_list_item_1, names);
EditSiteList.this.setListAdapter(la);
listview.invalidateViews();
this code works fine for me.

You should use only one adapter binded with the list of data you need to list
When you need to remove and replace all items, you have to clear all items from data-list using "list.clear()" and then add new data using "list.addAll(List)"
here an example:
List<String> myList = new ArrayList<String>();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, myList);
listview.setAdapter(adapter);
listview.setOnItemClickListener(this);
populateList(){
List<String> result = getDataMethods();
myList.addAll(result);
adapter.notifyDataSetChanged();
}
repopulateList(){
List<String> result = getDataMethods();
myList.clear();
myList.addAll(result);
adapter.notifyDataSetChanged();
}

Try this code, it works for me.
public class Third extends ListActivity {
private ArrayAdapter<String> adapter;
private List<String> liste;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2" };
liste = new ArrayList<String>();
Collections.addAll(liste, values);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, liste);
setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
liste.remove(position);
adapter.notifyDataSetChanged();
}
}

At first you should remove the item from your list. Later you may empty your adapter and refill it with new list.
private void add(final List<Track> trackList) {
MyAdapter bindingData = new MyAdapter(MyActivity.this, trackList);
list = (ListView) findViewById(R.id.my_list); // TODO
list.setAdapter(bindingData);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
// ShowPlacePref(places, position);
AlertDialog.Builder showPlace = new AlertDialog.Builder(
Favoriler.this);
showPlace.setMessage("Remove from list?");
showPlace.setPositiveButton("DELETE", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
trackList.remove(position); //FIRST OF ALL REMOVE ITEM FROM LIST
list.setAdapter(null); // THEN EMPTY YOUR ADAPTER
add(trackList); // AT LAST REFILL YOUR LISTVIEW (Recursively)
}
});
showPlace.setNegativeButton("CANCEL", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
showPlace.show();
}
});
}

It's simple .First you should clear your collection and after clear list like this code :
yourCollection.clear();
setListAdapter(null);

You can also use listView.setOnItemLongClickListener to delete selected item.
Below is the code.
// listView = name of your ListView
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int
position, long id) {
// it will get the position of selected item from the ListView
final int selected_item = position;
new AlertDialog.Builder(MainActivity.this).
setIcon(android.R.drawable.ic_delete)
.setTitle("Are you sure...")
.setMessage("Do you want to delete the selected item..?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which)
{
list.remove(selected_item);
arrayAdapter.notifyDataSetChanged();
}
})
.setNegativeButton("No" , null).show();
return true;
}
});

//try this:
String text = ( (TextView) view).getText().toString();
adapter.remove(text);

Related

Android ListView Removing Item on click

I am trying to remove an item from the list when I click on the selected item but I get an error on logcat saying that the removeViewAt method is not supported on AddapterView. Any idea of what I could use here in order to achieve this ?
Many thanks.
Here is my code.
listView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
listView.removeViewAt(position);
listView.invalidateViews();
}
});
}
Try this:
ArrayList<String> arrlist=new ArrayList<String>();
arrlist.add("A");
arrlist.add("B");
arrlist.add("C");
arrlist.add("D");
ListView listView = (ListView) findViewById(R.id.mylist);
String[] items = { "Milk", "Butter", "Yogurt", "Toothpaste", "Ice Cream" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, items);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
items.remove(position);
adapter.notifyDataSetChanged();
}
});
}
This fades away the clicked item using Animation, Requires API level 16
private List<String> myList;
File file;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.listerX);
myList = new ArrayList<String>();
File directory = Environment.getExternalStorageDirectory();
file = new File( directory + "/myAppCache/" );
File list[] = file.listFiles();
for( int i=0; i< list.length; i++)
{
myList.add( list[i].getName() );
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
final String item = (String) parent.getItemAtPosition(position);
view.animate().setDuration(2000).alpha(0)
.withEndAction(new Runnable() {
#Override
public void run()
{
Toast.makeText(getApplicationContext(), ""+item,
Toast.LENGTH_LONG).show();
}
});
}
});
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, myList);
listView.setAdapter(adapter); //Set all the file in the list.
}
you are populate list with any array or collection item
Then remove item at position of clicked position.
And now notify adapter by calling adapter.notifydatasetchange();
Enjoy your code

ListView onClick update clears the list

I have the following code that's supposed to remove the item that is clicked on:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String itemValue = (String) listView.getItemAtPosition(position);
email_addresses.remove(position);
String size = Integer.toString(email_addresses.size());
Log.d("Size: ", size);
//listView = (ListView) findViewById(R.id.email_list);
//ArrayAdapter<String> adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, android.R.id.text1, email_addresses);
//listView.setAdapter(adapter);
ArrayAdapter<String> adapter = new ArrayAdapter<>(mainAppContext, android.R.layout.simple_list_item_1, android.R.id.text1, email_addresses);
((ListView)parent).setAdapter(adapter);
parent.refreshDrawableState();
}
When I click on an item the list is cleared and nothing is displayed. The size is the correct value and the list can be rebuilt but I am unable to get this code to work.
Thank you
Instead of creating a whole new Adapter each time, have you thought about simply making your Adapter a member variable and calling notifyDataSetChanged?
ArrayAdapter<String> adapter = new ArrayAdapter<>(mainAppContext, android.R.layout.simple_list_item_1, android.R.id.text1, email_addresses);
((ListView)parent).setAdapter(adapter);
Becomes:
mAdapter.notifyDataSetChanged();
Define your list and adapter as instant variables and also You have to notify the adapter in order to make the deletion affect ,
Try this ,
listview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
email_addresses.remove(position);
adapter .notifyDataSetChanged();
}
});

Select all items using a button in a custom listview

I would like to select and deselect all the items in the listview using "SelectAll" and "DeselectAll" buttons. I wrote the code for SelectAll but it throws a NullPointException. I couldn't find the bug in my code. Can someone point out the error in my code.
final ListView list;
String[] listItems = { "Enabled" };
list = (ListView)findViewById(R.id.list);
list.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, getResources().getStringArray(R.array.facilities)));
list.setItemsCanFocus(false);
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
CheckedTextView ctv = (CheckedTextView)arg1;
//other functionality!
}
});
OnClickListener clickListener = new OnClickListener() {
#Override
public void onClick(View view) {
int itemCount = getListView().getCount();
System.out.print(itemCount);
for (int i = 0; i < itemCount; i++){
list.setItemChecked(i, true);
//getListView().setItemChecked(i, chk.isChecked());
}
}
};
Button button = (Button) findViewById(R.id.selectAll);
button.setOnClickListener(clickListener);
try to use below code...
private OnClickListener checkAllCheckboxes = new OnClickListener()
{
public void onClick(View v)
{
ListView lv = getListView();
int size = getListAdapter().getCount();
if(lv.isItemChecked(0))
{
for(int i = 0; i<=size; i++)
{
lv.setItemChecked(i, false);
}
}
}
}
};
You Can create One ArrayList of data class
class data
{
boolean chekced=false
create setter and getter of this
}
Create ArrayList of Data Class intially Chekced is false in all arraylist items
When select is called set all items to true
Then moify adpater and call notifyDatasetChanged on listView
This is how you can do this

Updating listview in Android

I've made a listview for some games, and when a game is deleted i'd like it to vanish in the listview. I'm trying to use adapter.notifyDataSetChanged(), but i can't get it to work, can you help me?
public static final String MY_SETTINGS = "MySettings";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
DBHelpeR entry = new DBHelpeR(Loadmenu.this);
entry.open();
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.list_item,entry.getGameNames());
setListAdapter(adapter);
entry.close();
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setBackgroundResource(R.drawable.background);
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
lv.setOnItemLongClickListener(new OnItemLongClickListener(){
public boolean onItemLongClick(AdapterView<?> parent, final View view,
int position, long id) {
String gamename = ((TextView) view).getText().toString();
builder.setTitle("Slet " + gamename + "?");
builder.setItems(new CharSequence[]{"Slet"} , new DialogInterface.OnClickListener() {
// Click listener
public void onClick(DialogInterface dialog, int item) {
DBHelpeR entry = new DBHelpeR(Loadmenu.this);
entry.open();
int game_id = entry.getGameID(((TextView) view).getText().toString());
Log.d("load",Integer.toString(game_id));
entry.deleteGame(game_id);
entry.close();
adapter.notifyDataSetChanged();
}
});
builder.show();
return true;
}
});
}
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.list_item,entry.getGameNames());
replace the above line with below :::
ArrayList<String> entries = entry.getGameNames();
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.list_item,entries);
and when you delete just dcall the below two lines again::
entries = entry.getGameNames();
adapter.notifyDataSetChanged();
Updated::
Again before calling adapter.notifyDataSetChanged(); call the below lines::
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.list_item, entry.getGameNames());
setListAdapter(adapter);
call
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.list_item,entry.getGameNames());
setListAdapter(adapter);
Again before calling
adapter.notifyDataSetChanged();
Note: make sure you have changed the array for the change to be visible.

show an open spinner

I have Async task to provide me list of some cities and after I have the list, I want to show me an OPEN spinner directly without any dialogs. My code opens spinner with propper list, but clickListener doesn't seems to work.
my code:
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, spinnerCities);
listAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner = new Spinner(this);
spinner.setAdapter(listAdapter);
spinner.performClick();
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> aView, View selectedItemView,
int position, long longID) {
System.out.println("ON ITEM CLICK LISTENER HERE");
}
public void onNothingSelected(AdapterView<?> aView) {
}
});
What I am missing here?
So after several hours, I figured it out. I need to use Dialog, but result is the same I have wanted. Here is source in case, someone is find useful.
private void MyMethod(){
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item,
(String[])MyClass.getListOfCities().toArray());
AlertDialog.Builder ad = new AlertDialog.Builder(this);
ad.setIcon(icon);
ad.setTitle("Title");
ad.setSingleChoiceItems( listAdapter, -1, new OnClickListener() {
public void onClick(DialogInterface dialog, int position) {
// DO something when I click on item
dialog.dismiss();
}
});
ad.show();
}

Categories

Resources