中易网

SimpleAdapter获取网络数据并填充LISTVIEW

答案:2  悬赏:10  
解决时间 2021-11-09 16:32
  • 提问者网友:無奈小影
  • 2021-11-08 18:13
因为安卓4不支持在主线程访问网络,就使用了Handler,可以正常获取数据并填充TEXTVIEW,但在使用SimpleAdapter并填充LISTVIEW时却没有反应,请问是什么原因?
private TextView tv = null;
private Button btn = null;
private ListView lv = null;
private SimpleAdapter sa = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv1);
btn = (Button) findViewById(R.id.button1);
lv = (ListView) findViewById(R.id.ls);
tv.setText("测试listview");
lv.setAdapter(sa);// HandlerThread ht=(HandlerThread)
final Handler myhandler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == 1) {
System.out.println("--------------->" + msg.obj);
sa = (SimpleAdapter) msg.obj;
sa.notifyDataSetChanged();
tv.setText((String) msg.obj.toString());
}
}
};
btn.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new Thread() {
public void run() {
try {
Thread.sleep(2000);
} catch (Exception e) {
// TODO: handle exception
}

Message msg = new Message();
msg.what = 1;
ArrayList> al = new ArrayList>();
HashMap hm = new HashMap();
hm.put("name", "wfgdz");
hm.put("phone", "138238");
al.add(hm);
sa = new SimpleAdapter(MainActivity.this, al,
R.layout.listview_item, new String[] { "name",
"phone" }, new int[] { R.id.nametv,
R.id.phonetv });
msg.obj = sa;
myhandler.sendMessage(msg);
}
}.start();
}
});
}
最佳答案
  • 二级知识专家网友:狙击你的心
  • 2021-11-08 19:52
lv(你的listview)没有setAdapter,所以没作用。在sa.notifyDataSetChanged();执行之前,调用lv.setAdapter(sa);
全部回答
  • 1楼网友:茫然不知崩溃
  • 2021-11-08 20:46
一般你的视图适配器还有一个类似于list的存储数据list 通过把数据添加到list,然后调用适配器的一个方法通知视图更新 adapter.notifydatasetchanged();
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息!
大家都在看
推荐信息