tags:

views:

112

answers:

2

Hi guys, I am trying to get this code to run, but I get an IllegalStateException when I run this code saying that the content of the listview wasn't notified, yet I have a notification upon updating the data. This is a custom listview adapter. Here is the relevant part of my code:

class LoadingThread extends Thread {
    public void run() {
        int itemsOriginallyLoaded = 0;
        synchronized( items ) {
            itemsOriginallyLoaded = items.size();
        }
        for( int i = itemsOriginallyLoaded ; i < itemsToLoad ; ++i ) {
            Log.d( LOG_TAG, "Loading item #"+i );
            //String item = "FAIL";
            //try {
            String item = "FAIL";
            try {
                item = stockGrabber.getStockString(dataSource.get(i));
            } catch (ApiException e) {
                Log.e(LOG_TAG, "Problem making API request", e);
            } catch (ParseException e) {
                Log.e(LOG_TAG, "Problem parsing API request", e);
            }
            //} catch (ApiException e) {
            //  Log.e(TAG, "Problem making API request", e);
            //} catch (ParseException e) {
            //  Log.e(TAG, "Problem parsing API request", e);
            //}
            synchronized( items ) {
                items.add( item );
            }
            itemsLoaded = i+1;
            uiHandler.post( updateTask );
            Log.d( LOG_TAG, "Published item #"+i );
        }
        if( itemsLoaded >= ( dataSource.size() - 1 ) )
            allItemsLoaded = true;
        synchronized( loading ) {
            loading = Boolean.FALSE;
        }
    }
}

class UIUpdateTask implements Runnable {
    public void run() {
        Log.d( LOG_TAG, "Publishing progress" );
        notifyDataSetChanged();
    }
}
A: 

Using Threads in android apps isn't good idea. Try using AsyncTask which provides more convenient way to use background tasks

WarGoth
FAIL. Using threads IS a good idea, and necessary in many cases so that you don't block the UI thread and cause ANRs.
Brad Hein
`AsyncTask` wraps a managed pool of background threads. Forking your own threads, outside of `AsyncTask`, is occasionally necessary but ideally avoided for simplicity. I believe Mr. Goth was referring to the use of `Thread` objects.
CommonsWare
Sure, I mean Thread objects
WarGoth
+2  A: 

I don't know what items is. If items is an ArrayAdapter, you cannot modify the contents of the ArrayAdapter safely from a background thread (whether a thread you fork or an AsyncTask).

CommonsWare