Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Listview keeps old items after adapter changes

I try to change the content of a Listview in Android. After that I want the list to be redrawn. Unfortunately the list elements change, but the old items are displayed in the background. If there are less items in the new list it seems like the old items are still part of the list, as they are still displayed, even though they are not clickable. If I jump out of the app via the Android Taskmanager and afterwards open the app again, the list gets displayed correctly! Therefore I think it must be a problem with refresh.

How do I try to achieve it:

As the complete content changes I create a new adapter that I pass to the ListView. In my code "favorites" is the new Array that I pass to the adapter. I also try to clear the list and invalidate it. all of this happens in the UI thread (onPostExecute of AsyncTask)

    MyAdapter newAdapter = new MyAdapter(
            context, favorites);
    MyAdapter current_adapter = (MyAdapter) myList.getAdapter(); 
    if((current_adapter!=null)){
    current_adapter.clear();}

    myList.setAdapter(null); //inserted this because of answers, but with no effect.
    myList.setAdapter(newAdapter);
    myList.invalidateViews();

The clear method of the adapter:

    public void clear(){
    items.clear();
    notifyDataSetChanged();
    }

As you can see I tried all of the solutions to similar problems her on stackoverflow. Unfortunately nothing worked...

Thanks in advance for any ideas how to solve this.

Edit:

I have also tried to set the adapter null before passing the new one, also with no effect. .setAdapter(null);

Also if I open the keyboard by clicking in a editText, the screen refreshs and the list is displayed correctly.

like image 844
AndroidDev23 Avatar asked Sep 04 '13 10:09

AndroidDev23


2 Answers

Have you tried myList.setAdapter(null); ?

like image 196
Omar Farhat Avatar answered Oct 13 '22 01:10

Omar Farhat


I solved the problem by filling the remaining space under the list with a layout with more layout_weight than the ListView. This way the "extra" lines are hidden.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/main_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/transparent"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/main_list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>

    <LinearLayout
        android:id="@+id/aux_layout"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="@color/transparent"
        android:orientation="vertical" />

</LinearLayout>
like image 30
Tanausú González Avatar answered Oct 13 '22 01:10

Tanausú González