Santhosh
Santhosh

Reputation: 5016

ListView Adapter issue in android

Here is my code to browse through all folders in device.

private File file;
private List<String> directoriesList;
private ListView listView ;
private ArrayAdapter<String> adapter;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.folder_browse_screen);
    listView = (ListView) findViewById(R.id.foldersListView);

    directoriesList = new ArrayList<String>();

    file = new File("/mnt");

     File list[] = file.listFiles();
    if (list != null && list.length >= 1) {
        for (int i = 0; i < list.length; i++) {
            File f = list[i];
            if (!f.isHidden() && f.canRead() && f.isDirectory()) {
                directoriesList.add(f.getName());
            }
        }

        adapter  = new ArrayAdapter<String>(this, R.layout.list_row, R.id.folder_name, directoriesList);
        listView.setAdapter(adapter);
}

OnItemClick :

@Override  
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {  
    try {
        File temp_file = new File(file, directoriesList.get(position));

        if (!temp_file.isHidden() && temp_file.canRead() && temp_file.isDirectory()) {
            file = new File(file, directoriesList.get(position));
            File list[] = file.listFiles();
            directoriesList.clear();

            if (list != null && list.length >= 1) {  
                for (int i = 0; i < list.length; i++) {
                    File f = list[i];
                    if (!f.isHidden() && f.canRead() && f.isDirectory()) {
                        directoriesList.add(f.getName());
                    }
                } 
                adapter.notifyDataSetChanged(); 
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Exception : java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. [in ListView(2131034114, class android.widget.ListView) with Adapter(class android.widget.ArrayAdapter)]

Where am'I using threads? Why it is force closing on click of any empty folder? Please help me.

Upvotes: 1

Views: 316

Answers (1)

GreyBeardedGeek
GreyBeardedGeek

Reputation: 30088

I believe that the problem is that in the onClick handler, you always clear() the list, but then only notify the adapter if the selected directory is not empty.

So, when an empty directory is clicked, the list is changed (cleared), but the adapter is not notified.

Therefore the error message, "The content of the adapter has changed but ListView did not receive a notification".

Ignore the stuff about threads - it's just a guess by the author of the error message, not a definitive indication that you've modified the UI from a background thread.

Upvotes: 3

Related Questions