Saurabh
Saurabh

Reputation: 157

How to refresh a ListView in the activity

I have a ListActivity class. It has a button which sorts the item according to one of their attributes. But it so happens that the item are getting sort by their name but upon clicking the item of its original position is getting executed. Here is the code snippet :

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.playlist);

        mButton = (ToggleButton) findViewById(R.id.mButton);

        ArrayList<myObject> ListData = new ArrayList<myObject>();

        back = (ImageButton) findViewById(R.id.backButton);
        label = (TextView) findViewById(R.id.likethis);
        label.setText("List");
        inputSearch = (EditText) findViewById(R.id.inputSearch);

        //Manager -- class that reads from the sdcard
        Manager plm = new Manager();

        // get all files from sdcard
        //getList() function of Manager class
        //List declared outside oncreate()
        this.List = plm.getList(); 

        final ArrayList<myObject> backUp = new ArrayList<myObject>(songsList);

        if(sortCalled) {
            mButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.m_checked));
            mButton.setChecked(true);
            Collections.sort(List);

            notifyDataChanged(List);
        }
        else {
            mButton.setBackground(getResources().getDrawable(R.drawable.m_unchecked));
            mButton.setChecked(false);
            notifyDataChanged(backUp);
        }

        back.setOnClickListener(new OnClickListener(){

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

        });

        inputSearch.addTextChangedListener(new TextWatcher(){

            @Override
            public void afterTextChanged(Editable arg0) {
                // TODO Auto-generated method stub
                adapter.notifyDataSetChanged();
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
                // TODO Auto-generated method stub

            }

            @Override 
            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {
                // TODO Auto-generated method stub
                //ArrayList <Song> temp;
                ((SimpleAdapter) PlayListActivity.this.adapter).getFilter().filter(s, new Filter.FilterListener() {

                    public void onFilterComplete(int count) {
                        // TODO Auto-generated method stub
                        adapter.notifyDataSetChanged();
                    }
                });
                adapter.notifyDataSetChanged();


            }

        });

        mButton.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if(mButton.isChecked()){
                    mButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.m_checked));
                    Collections.sort(List);
                    sortCalled = true;
                    notifyDataChanged(List);
                }
                else{
                    sortCalled = false;
                    mButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.m_unchecked));
                    notifyDataChanged(backUp);
                }
            }

        });
    }

    public void settingListAdapter(SimpleAdapter adapter){
        setListAdapter(adapter);
        ListView lv = getListView();
        // listening to single listitem click
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting listitem index
                int Index = position;

                // Starting new intent
                Intent in = new Intent(getApplicationContext(),
                        MainActivity.class);
                // Sending Index to MainActivity
                in.putExtra("Index", Index);
                setResult(100, in);
                // Closing ListView
                finish();
            }
        });
    }

    public void notifyDataChanged(ArrayList<Song> songsList) {
        // TODO Auto-generated method stub
        setListAdapter(null);
        sortCalled = true;
        ArrayList<myObject> songsListData = new ArrayList<myObject>();

        for (int i = 0; i < songsList.size(); i++) {
            // creating new HashMap
            myObject ob = sList.get(i);

            // adding HashList to ArrayList
            ListData.add(ob);
        }

        ArrayList<HashMap<String, String>> array = new ArrayList<HashMap<String,String>>();
       // int j = 0;
        for(myObject i : ListData){
            HashMap<String, String> feed = new HashMap<String, String>();
            feed.put("Title", i.getTitle());
            array.add(feed);

        }
        BaseAdapter adapter1;
       // int i = 0;
        // Adding menuItems to ListView
         adapter1 = new SimpleAdapter(this, array,
                R.layout.list_item, new String[]{"Title" }, new int[] {
                        R.id.Title });

        setListAdapter(adapter1);
        adapter1.notifyDataSetChanged();

        ListView lv = getListView();
        // listening to single listitem click

        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting listitem index
                int Index = position;

                // Starting new intent
                Intent in = new Intent(getApplicationContext(),
                        MainActivity.class);
                // Sending songIndex to MainActivity
                in.putExtra("Index", Index);
                setResult(100, in);
                // Closing ListView
                finish();
            }
        });

Upvotes: 0

Views: 3200

Answers (3)

Just Variable
Just Variable

Reputation: 877

Everytime you make a change to adapter you should call notifyDataSetChanged() in UIThread

Please check this video to understand listView better

Edit
For an ArrayAdapter, notifyDataSetChanged only works if you use the add, insert, remove, and clear functions on the Adapter.

When an ArrayAdapter is constructed, it holds the reference for the List that was passed in. If you were to pass in a List that was a member of an Activity, and change that Activity member later, the ArrayAdapter is still holding a reference to the original List. The Adapter does not know you changed the List in the Activity.

Your choices are:

Use the functions of the ArrayAdapter to modify the underlying List (add, insert, remove, clear, etc.) Re-create the ArrayAdapter with the new List data. (Uses a lot of resources and garbage collection.) Create your own class derived from BaseAdapter and ListAdapter that allows changing of the underlying List data structure. Use the notifyDataSetChanged every time the list is update. To call it on the UI-Thread use the runOnUiThread method of the Activity. Then notifyDataSetChanged will work.

Upvotes: 1

Jay
Jay

Reputation: 1492

You could try the Adapter.notifyDataSetChanged() function. It might work.

If you are using a SimpleCursorAdapter, calling requery() on the cursor attached to the adapter will automatically refresh the adapter and attached view.

If it's BaseAdapter content changes, you call BaseAdapter.notifyDataSetChanged() which will tell the ListView to update itself.

In other words you only need to make the following tiny change:

public void setValue(Object newValue) {
     this.value = newValue;
     notifyDataSetChanged();
}

Actually, since you're changing the state of an existing item (rather than adding new ones etc) then notifyDataSetInvalidated() would be a better choice.

Upvotes: 0

Naveen Kumar
Naveen Kumar

Reputation: 3818

I think you should try this.when you sort the data of your listview.it is working me perfectly

 adapter.notifyDataSetChanged();

Upvotes: 2

Related Questions