Android: Update Listview after Thread loads data from the net

后端 未结 3 1691
小蘑菇
小蘑菇 2020-12-24 15:01
  1. I like that my GUI appears immediately when the user starts the app.
  2. Then some data (text, pictures) gets loaded in the background (like YouTube app).
相关标签:
3条回答
  • 2020-12-24 15:38

    I have this same problem... and I got excited when I came across this question. But no answer? :-(

    After, letting the problem sit for about two weeks I found the solution here:

    Long story short:

    Quote from above link:

    We must use a Handler object because we cannot update most UI objects while in a separate thread. When we send a message to the Handler it will get saved into a queue and get executed by the UI thread as soon as possible.

    Once you check out the code you see get what the author is saying.
    NOTE: Even with a handler, Android may not let you update a view object from the thread's run() method. I got this error:

    05-31 02:12:17.064: ERROR/AndroidRuntime(881):
    android.view.ViewRoot$CalledFromWrongThreadException: 
    Only the original thread that created a view hierarchy can touch its views.
    

    To get around it I updated an array of data in my run() method and used that array to update the view in the handler's handleMessage() method.

    I hope this helps others out there.

    0 讨论(0)
  • 2020-12-24 15:47

    You may use the slowAdapter to refresh the View:

    SlowAdapter slowAdapter = new SlowAdapter(this);
    
    list.setAdapter(slowAdapter);
    slowAdapter.notifyDataSetChanged();
    
    0 讨论(0)
  • 2020-12-24 15:54

    Just found it myself while reading this thread and trying around.

    Short: AsyncTask's method onProgressUpdate can touch the view: http://developer.android.com/reference/android/os/AsyncTask.html#onProgressUpdate(Progress...)

    Background: I needed to call requery on my cursor so a ListView kept being updated while the task fills the database. The requery call made in doInBackground failed with the mentioned CalledFromWrongThreadException but same code in onProgressUpdate works.

    0 讨论(0)
提交回复
热议问题