4

I have used a List and an Arrayadapter to put strings in a Listview. Now I want to remove the selected Item. I have tried the following code, but it's not working well. How can I fix this?

Here's my code:

TextView t1;
String[] temp;
mylist = (ListView) findViewById(R.id.list);
final List<String> wordList = Arrays.asList(temp);
adapter = new ArrayAdapter<String>(this,
                                   android.R.layout.simple_list_item_multiple_choice, 
                                   wordList);
delete.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View arg0) {
       int index = mylist.getSelectedItemPosition();
       int count=mylist.getCount();
       for(int i=0;i<=count;i++) {
           if (index >= 0) {
               t1.setText(wordList.remove(index));
           }
           adapter.notifyDataSetChanged();
       } 
   }
});

Here's more source code:

    public class Edit extends Activity {
        SharedPreferences sharedpref;
        ListView mylist;
        String[] temp;
        String name, 
        ArrayAdapter<String> adapter;
        Button save, delete, cancel;
        TextView t1;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.edit);
            mylist = (ListView) findViewById(R.id.list);
            cancel = (Button) findViewById(R.id.cancel1);
            save = (Button) findViewById(R.id.save1);
            delete = (Button) findViewById(R.id.delete1);
            t1=(TextView)findViewById(R.id.textView1);
            sharedpref = PreferenceManager
                    .getDefaultSharedPreferences(getApplicationContext());
            name = sharedpref.getString("Visible_selected", "");

            String delimiter = "\n";
            temp = name.split(delimiter);

            mylist.setItemsCanFocus(true);
            mylist.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
             final List<String> wordList = Arrays.asList(temp);  

            adapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_list_item_multiple_choice, wordList);
            mylist.setAdapter(adapter);
            save.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub

                }
            });

            delete.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    mylist.setOnItemClickListener(new OnItemClickListener() {
                        private String getSelectedItemOfList;
                        @Override
                        public void onItemClick(AdapterView<?> arg0, View arg1,
                                int arg2, long arg3) {
                            // TODO Auto-generated method stub
                             getSelectedItemOfList = sortedList.get(arg2).getStr_movieParam();


                }
            });

            cancel.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub

                }
            });

        }

    }

Here's my updates code:

enter code here

delete.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
         adapter.remove(getSelectedItemOfList);
         adapter.notifyDataSetChanged();
            }
        });
        mylist.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                // TODO Auto-generated method stub
                SparseBooleanArray checkedPositions =mylist.getCheckedItemPositions();
                if(checkedPositions.get(arg2)==true){
                getSelectedItemOfList = (String) mylist.getItemAtPosition(arg2);
                t1.append(getSelectedItemOfList.toString()+"\n");}
            }
        });
user1580945
  • 91
  • 2
  • 2
  • 10
  • is this giving any error or exception – Avi Kumar Aug 14 '12 at 06:23
  • no..Its not showing any error.. – user1580945 Aug 14 '12 at 06:25
  • what button? how does "simple_list_item_multiple_choice" look like? how do you know which have been selected? You are showing such a little thing. What i normally do is delete from my arraylist, and then make a new adapter, set it to the list view, and call notifydatasetchanged. – Anders Metnik Aug 14 '12 at 06:26
  • set onitemclick for the list and not for the button – G_S Aug 14 '12 at 06:27
  • @sharath G ..ya i can do as you said like onitem for list..,but i want show the changes when i click the delete button.. – user1580945 Aug 14 '12 at 06:31
  • then you have to save the list item clicked which we get from the onitemclick of the listview and next when you click the button remove it from the arrayadapter – G_S Aug 14 '12 at 06:32

10 Answers10

6

Try to implement the onitemclickListener and get the item id and delete the item clicked in the arrayadapter and next call adapter.notifyDataSetChanged();

G_S
  • 7,068
  • 2
  • 21
  • 51
2

Try this...

        mylist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapter, View v, int position,
                                long arg3) {
            String value = (String) adapter.getItemAtPosition(position);
            adapter.remove(value);
            adapter.notifyDataSetChanged();               
        }
    });
Apollon
  • 311
  • 7
  • 29
  • Android Studio 2.3.3 => Here .remove(value) and .notifyDataSetChanged() are adapter class methods not AdapterView> methods. For example if the Adapter class name is ProductAdapter and it's object name is prodAdapter then Product prod = (Product) adapter.getItemAtPosition(position); prodAdapter.remove(prod); prodAdapter.notifyDataSetChanged(); – Saravanan Sachi Jun 28 '17 at 16:56
1

I think you should use OnItemClickListener() for the listview so that when you select/click any list item you will get name of selected item then you can perform deletion operation.

Try this.

    mylist.OnItemClickListener(listenerOflistView);

private OnItemClickListener listenerOflistView = new OnItemClickListener() {
    private String getSelectedItemOfList;

    public void onItemClick(AdapterView<?> view, View view1, int pos,
            long arg3) {
        // TODO Auto-generated method stub

    getSelectedItemOfList = mylist.get(pos).toString(); // here you will get selected item name.
      }
    }

Hope this will help you.

Akshay
  • 2,506
  • 4
  • 34
  • 55
  • Sorry i couldnt use you the above code..its shows me an error in sorted list..:( – user1580945 Aug 14 '12 at 06:49
  • why is it so? Can you please post complete source code so that i can suggest something. – Akshay Aug 14 '12 at 06:52
  • Not in logcat...Its shows me to create a localVariable..SortedList is a kinda property rite? – user1580945 Aug 14 '12 at 07:11
  • I have change my post SortedList is list which I am using in my app.plz update your code – Akshay Aug 14 '12 at 07:16
  • please post your code so that we can help you in one or the other way – G_S Aug 14 '12 at 07:35
  • I have posted my entire code..But stil am getting the error even after i made changes to mylist.get(pos).toString(); – user1580945 Aug 14 '12 at 07:48
  • what is the local variable that is showing error and where did you post the code? i found the code with no necessary modifications. can you post the error please – G_S Aug 14 '12 at 08:07
  • I think you are getting error bcoz you are trying to use listener inside listener.Instead of that uses separate listener for delete and listview.And declare `getSelectedItemOfList` as global variable so that you can use it in listener of delete button. – Akshay Aug 14 '12 at 09:05
  • Ya..i have used separate listener..And i have used this..adapter.remove(getSelectedItemOfList);adapter.notifyDataSetchange();..but it shows me force close.. – user1580945 Aug 14 '12 at 09:44
  • mylist.setonitem{getSelectedItemOfList = (String) mylist.getItemAtPosition(arg2); t1.append(getSelectedItemOfList.toString()+"\n");}} – user1580945 Aug 14 '12 at 09:49
  • Plz remove `getSelectedItemOfList` from your wordList and assign new list to adapter. – Akshay Aug 14 '12 at 09:50
  • delete.setonclick{getSelectedItemOfList);adapter.notifyDataSetchange();}...am using this one – user1580945 Aug 14 '12 at 09:50
  • See what you have to do is you have to compare `getSelectedItemOfList` with your list.Then remove that item form your list and create new adapter and assign that list(i.e. updated list) that's it. – Akshay Aug 14 '12 at 10:14
  • adapter1.add (mylist.getItemAtPosition(arg2).toString()); adapter1.notifyDataSetChanged(); mylist.setAdapter(adapter1); i couldnt update the list with selected item.. – user1580945 Aug 14 '12 at 12:50
1

see this code which help you to understand how to remove items in listview.

private ArrayList<String> students = new ArrayList<>();
private ArrayAdapter<String> arrayAdapter;
private ListView myListView;
private int getSelectedIndex = -1;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    myListView = (ListView) findViewById(R.id.myListView);
    students.add("rahim");
    students.add("karim");
    students.add("sumon");
    students.add("rakib");
    students.add("porag");
    arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, students);
    myListView.setAdapter(arrayAdapter);
    myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {


        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Toast.makeText(getApplicationContext(), "hello " + students.get(position), Toast.LENGTH_LONG).show();
            MainActivity.this.getSelectedIndex = position;
            for (int i = 0; i < myListView.getChildCount(); i++) {
                if(position == i ){
                    myListView.getChildAt(i).setBackgroundColor(Color.BLUE);
                }else{
                    myListView.getChildAt(i).setBackgroundColor(Color.TRANSPARENT);
                }
            }


        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);//Menu Resource, Menu
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.add:
            Toast.makeText(getApplicationContext(), "Item 1 Selected", Toast.LENGTH_LONG).show();
            return true;
        case R.id.delete:
            if(this.getSelectedIndex!=-1){
                students.remove(this.getSelectedIndex);
                this.getSelectedIndex = -1;

                arrayAdapter.notifyDataSetChanged();
                myListView.setAdapter(arrayAdapter);

            }
            return true;
        default:
            return false;
    }
}
tapos ghosh
  • 2,114
  • 23
  • 37
0

I would say the best way to do this (the really best way is a custom adapter) is to keep a copy of your arraylist of items in your class. Then when delete is called remofve the item form your copy of the arraylist and re-init the listview.

MikeIsrael
  • 2,871
  • 2
  • 22
  • 34
0

First thing i want to tell you that code you have written is wrong... May be you want the context menu on listview..

if you are getting the position of selected item then you can have

adapter.removeItem(adapter.getItem(position));
adapter.notifyDatasetChanged()

may this help you

NullPointerException
  • 3,978
  • 4
  • 34
  • 52
0

replace

delete.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            mylist.setOnItemClickListener(new OnItemClickListener() {
                private String getSelectedItemOfList;
                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1,
                        int arg2, long arg3) {
                    // TODO Auto-generated method stub
                     getSelectedItemOfList = sortedList.get(arg2).getStr_movieParam();
        }
    });

with

 mylist.setOnItemClickListener(new OnItemClickListener() {
                private String getSelectedItemOfList;
                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1,
                        int arg2, long arg3) {
                    // TODO Auto-generated method stub
                     getSelectedItemOfList = sortedList.get(arg2).getStr_movieParam();
        }
    });

and

delete.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {

                 adapter.remove(getSelectedItemOfList );
adapter.notifydatasetChanged

        }
    });

check this one

Akshay
  • 2,506
  • 4
  • 34
  • 55
G_S
  • 7,068
  • 2
  • 21
  • 51
  • See my updated code above..am not using wordlist now..simply using arrayadapter with listview..i can get the selected item from mylist.setonitem but when i click delete to remove it from adapter..its shows force close – user1580945 Aug 14 '12 at 09:56
  • once please post your new code again as a new comment please (if you dont mind) – G_S Aug 14 '12 at 10:01
  • Is there any other way to create a new adapter and replace the listview elements with those new adapter values? – user1580945 Aug 14 '12 at 10:05
  • @SharathG You are making mistake while getting selected item please read my post carefully – Akshay Aug 14 '12 at 10:35
  • hey akshay.. Is there any necessity to get the particular value of the item. The person is just intersted in removing the particular item that is clicked.Doesnt it mean that we just need to get the position rather than getting the data over there?? so i feel getSelectedItemOfList = arg2 ; is sufficient. what do you say? – G_S Aug 14 '12 at 16:16
  • @Suji we are having notifydatasetChanged which is used to refresh the list when there is any modification in the items in the list. so there might be no need to create any other adapter for this. – G_S Aug 14 '12 at 16:20
  • @sharath n akshay..I have updated as said using notifydatasetchanged..ill update the code here in the name of update3..pls see to it n give your solutions.. – user1580945 Aug 15 '12 at 07:16
  • You are trying to remove all the elements from the adapter list. I think that's not the one you require. You even have a checkbox in your list view? – G_S Aug 15 '12 at 07:53
  • Sry please i made a mistake..I tel u clearly..the item which i get selected should remove from the list..And i have a checkbox in my listview by using simple_list_item_multiple_choice in adapter command..now i want to remove the items stored in getSelectedItemOfList.. – user1580945 Aug 16 '12 at 05:06
  • You are using multiselection of checkboxes? – G_S Aug 16 '12 at 05:08
  • adapter=new ArrayAdapter – user1580945 Aug 16 '12 at 05:21
  • yes i understood it. use something like SparseBooleanArray selectedPos = getListView() .getCheckedItemPositions(); or try checking the links in http://stackoverflow.com/questions/4831918/how-to-get-all-checked-items-from-a-listview – G_S Aug 16 '12 at 05:24
0

Try working with this code in the http://appfulcrum.com/2010/09/12/listview-example-3-simple-multiple-selection-checkboxes/

G_S
  • 7,068
  • 2
  • 21
  • 51
0

public class ListTest extends Activity {

String selectedItem;
ArrayAdapter<String> adapter;
ArrayList<String> newList = new ArrayList<String>();
ListView l1;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list_test);

  l1 = (ListView) findViewById(R.id.lsvSign);

    newList.add("Android");
    newList.add("iOS");
    newList.add("Mac");
    newList.add("Windows");
    newList.add("Linux");;
    Collections.sort(newList);
    adapter = new new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,newList);
    l1.setAdapter(adapter);  


  l1.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int position,
            long arg3) {            
         selectedItem = l1.getItemAtPosition(position).toString();           
       RemoveItem(selectedItem);

    }
});  
protected void RemoveItem(String item) {
    newList.remove(item);
    adp2.notifyDataSetChanged();
}   
}

}

Vinayak
  • 425
  • 4
  • 6
0

Try working code: listAdapter.remove(listAdapter.getItem(position)); mainListView.setAdapter( listAdapter );