1

我没有复制所有代码,因为它太长了,但要简洁:

我有一个函数(recup_list_internet),其中有一个线程,它从互联网(XML)检索数据,对其进行解码,并将每个“节点”分配给我的适配器中的一个元素。

在线程外进行解码时,一切正常。所以我修改它以在线程内使用,在其中创建一个 void run() 函数,显示我的progressDialog,解码,数据被很好地检索,很好地分配给我的地图(=new HashMap();),这里是出现问题

private void recup_list_internet()
{
final ArrayList<HashMap<String, String>> listItem = new ArrayList<HashMap<String, String>>();
final Context mContext=this.getBaseContext();


Thread t = new Thread()
{
    public void run()
    {/* the code here works fine, not displaying it to be more concise*/

    progressDialog.dismiss(); //works fine
    SimpleAdapter mSchedule = new SimpleAdapter (mContext, listItem, R.layout.affiche_boutique,new String[] {"img", "titre", "description","Prix","uniqueID"}, new int[] {R.id.img,R.id.titre, R.id.description,R.id.prix,R.id.uniqueID}); //works fine
    maListViewPerso.setAdapter(mSchedule); //doesn't work
    }
};
t.start();
}

这是我的日志猫:

11-04 19:20:33.070: E/recuperation phonster(546): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

似乎我无法在我的线程中“访问”maListViewPero ...(maListViewPerso 之前在我的 onCreate 代码中定义:

public class DisplayInternet  extends Activity{
private ListView maListViewPerso;
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.ceinture_lv);
    maListViewPerso = (ListView) findViewById(R.id.listviewperso);
    recup_list_internet();
}   

那么我可以把这条线放在哪里让它工作呢?“maListViewPerso.setAdapter(mSchedule);”

因为我已经尝试在我的线程之外(最终)声明 mSchedule 但在我的线程内,我无法访问它(因此,我无法在“t.start()”行之后使用它

4

2 回答 2

1

在你的线程中,使用:

View.post(Runnable r)

它基本上说“嘿,UI线程,为我执行这个东西” - 并将必须在UI线程中执行的所有代码放入可运行的代码 - 当您有一个线程从网络检索数据时特别有用(必须不在 UI 线程上运行)但必须在 UI 上发布结果(必须从 UI 线程完成)

例子:

view.post(new Runnable(){ 
    public void run(){
        //put all the code you want to be execute on the UI thread here
    }
});
于 2012-11-04T20:14:19.457 回答
0

尝试使用 runOnUi 函数从其他线程“触摸”主线程中的视图。

于 2013-07-03T14:45:25.880 回答