gpt4 book ai didi

android - 无法在线程中定义适配器

转载 作者:行者123 更新时间:2023-11-30 03:56:43 25 4
gpt4 key购买 nike

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

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

在线程外进行解码时,一切正常。所以我修改它以在线程内部使用,在其中创建一个 void run() 函数,显示我的 progressDialog,解码,数据被很好地检索,很好地分配给我的 map (=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()”行之后使用它

最佳答案

在你的线程中,使用:

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
}
});

关于android - 无法在线程中定义适配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13222195/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com