开发者

Modify parent class variables inside thread

开发者 https://www.devze.com 2023-03-13 07:37 出处:网络
I\'m trying to create an Android app in Java (using Ubuntu 11.10 with the latest Eclipse, ADT and latest Android SDK).

I'm trying to create an Android app in Java (using Ubuntu 11.10 with the latest Eclipse, ADT and latest Android SDK).

I have the below thread inside a function of its parent class:

n开发者_StackOverflow中文版ew Thread(new Runnable(){
            public void run(){
                    try{
                        list_items = rtm_instance.update_notes_list(list_items);
                        list_items.add("test");

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
        }
}).start();

list_items and rtm_instance are member variables of the class inside which the thread is written. It seems that list_items inside the thread is a snapshot of list_items in the parent class at the point of start()ing the thread.

Though rtm_instance.update_notes_list returns an updated notes list as expected, the changes made to list_items don't seem to modify the same variable in the parent class. Modifying list_items does nothing more than modify the said variable's copy inside the thread.

I want the modification to take place in the parent (UI) thread as well, so that an Android ListAdapter detects those and modifies the corresponding ListView. How do I modify the parent thread variable list_items from the child thread posted above?

Thanks!


You probably want the update to happen on the UI thread. You should post a runnable to the Handler from the UIThread. Alternatively you could call runOnUiThread. To have the list on the parent you could define a method on the parent called updateList(String val) and call this rather than changing the list directly.

0

精彩评论

暂无评论...
验证码 换一张
取 消