Update ListView in the main thread from another thread

前端 未结 6 811
北恋
北恋 2020-12-08 08:34

I have a separate thread running to get data from the internet. After that, I would like to update the ListView in the main thread by calling adapter.notifyDataSetChanged().

6条回答
  •  不思量自难忘°
    2020-12-08 09:18

    Overall good advice is http://android-developers.blogspot.com/2009/05/painless-threading.html

    Personally I use my custom thread (a class extending Thread ) but send response to the UI thread through a Message. So in the thread's run() function there is:

    Message msg;
    msg = Message.obtain();
    msg.what = MSG_IMG_SET;                     
    mExtHandler.sendMessage(msg);
    

    The UI thread defines a message handler.

    private Handler mImagesProgressHandler;
    
    public void onCreate(Bundle bundle) {
    
        mImagesProgressHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {             
                case LoadImagesThread.MSG_IMG_SET:
                    mArrayAdapter.setBitmapList(mImagesList);
                    mArrayAdapter.notifyDataSetChanged();
                    break;
                case LoadImagesThread.MSG_ERROR:
                    break;
                }
                super.handleMessage(msg);
            }
        };                 
    

    This is actually easier than AsyncTask.

提交回复
热议问题