Android 子线程中得到的键值对数组数据传递给主线程
很多小伙伴都知道有关数据库的操作需要放在子线程上,更新UI需要放在主线程上。
最近做的一个项目中遇到了这么一个问题,如何将子线程中得到的键值对数组数据传递给主线程。
private ListView lv_main;
//首先还是要声明一个SimpleAdapter适配器
private SimpleAdapter simpleAdapter;
private List<Map<String, Object>> data ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_yhgl);
//创建子线程
new Thread(new upDate()).start();
}
public class upDate implements Runnable{
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
//获取数据库数据
Database database = new Database();
List<Map<String, Object>> data = database.getData();
Message message = new Message();
message.obj = data;
handler.sendMessage(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Handler handler = new Handler(){
public void handleMessage(Message msg) {
Yhgl.this.data = (List<Map<String, Object>>) msg.obj;
simpleAdapter = new SimpleAdapter(Yhgl.this, data, R.layout.layout_yhglitem, new String[]{"bianhao", "name", "sex", "phone"},
new int[]{R.id.tv_bianhao, R.id.tv_name, R.id.tv_sex, R.id.tv_phone});
lv_main.setAdapter(simpleAdapter);
//刷新
simpleAdapter.notifyDataSetChanged();
};