简体   繁体   中英

How to handle prohibition of network-on-thread and need to update list adapter on UI thread?

Developing an Android application which uses CouchBase as its datastore. All interaction with Couch is via HTTP so it cannot be done on UI thread. This is ordinarily something we can work around pretty reasonably, but I'm hitting up against a rock and a hard place with this problem:

I'm trying to develop an encapsulated/ reusable CouchListAdapter . The concept being, fetch data from Couch in pages and then cache it. Say page size is 20 , so when initialized, fetch first 20 , then if asked for 21 , go get 21 - 40 .

Because of the prohibition of network on thread, my CouchViewLoader which has methods JSONObject getItemAt(int i) and int getCount() , when asked for data it does not have, has to kick off an asynchronous thread to get the data, then send out a broadcast handled by the enclosing activity which then rebinds/ notifies that data has changed.

I almost got it working but am stuck now where I get:

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.

How do I reconcile the inability to hit Couch on the UI thread and the need to only update my adapter from the UI thread??

Surely other people have solved this problem?

(Keep in mind, this is all designed around the idea that a given view may return more results than we can fit in memory or display on the screen.)

Have you considered an AsyncTask ?

You can do the hard work in doInBackground(...).

You can then update your ListAdapter in the onPostExecute(...) method.

You might want to consider using a content provider with loaders . Basically all information you need is located at those links.

For a general view:

  • Content providers provide data.
  • Loaders fetch data from content providers in background threads.
  • Once loaders have done the background jobs, they notify the UI (such as CursorAdapter , CursorTreeAdapter …) to update.

Your jobs are:

  • Have your content provider query data with the server. You can do network tasks in a content provider.
  • Decorate the UI with the data that loaders fetch.

About content providers, although they say that You don't need to develop your own provider if you don't intend to share your data with other applications. — but as they highly recommend using loaders (which they do support older APIs with support library ), and as my experiences, content providers will save your time a lot. I would say: just go with content provider :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM