Android如何将数据从子线程中传到主线程
privateintselect_username(){newThread(){@Overridepublicvoidrun(){Messagemsg=newMessag...
private int select_username(){
new Thread(){
@Override
public void run() {
Message msg = new Message();
v1 = a1.getText().toString();
v2 = a2.getText().toString();
v3 = a4.getText().toString();
dealData = new DealTest();
rs = dealData.select_username_Data(new UserBean(v1, v2, v3));
if (rs != null) {
Log.i("查询数据库成功", "run: ");
msg.what = 1;
handler.sendMessage(msg);
} else {
Log.i("查询数据库失败", "run: ");
msg.what = 0;
handler.sendMessage(msg);
}
}
}.start();
handler=new Handler() {
@Override
public void handleMessage(Message msg) {
Log.i("返回查询数据库结果", "nihao123"+msg.what);
if (msg.what > 0) {
j = 1;
} else {
j = 0;
}
Log.i("返回查询数据库结果", "i"+msg.what);
}
};
Log.i("返回查询数据库结果", "nihao"+j);
return j;
}
为什么我取的返回值始终是0? 展开
new Thread(){
@Override
public void run() {
Message msg = new Message();
v1 = a1.getText().toString();
v2 = a2.getText().toString();
v3 = a4.getText().toString();
dealData = new DealTest();
rs = dealData.select_username_Data(new UserBean(v1, v2, v3));
if (rs != null) {
Log.i("查询数据库成功", "run: ");
msg.what = 1;
handler.sendMessage(msg);
} else {
Log.i("查询数据库失败", "run: ");
msg.what = 0;
handler.sendMessage(msg);
}
}
}.start();
handler=new Handler() {
@Override
public void handleMessage(Message msg) {
Log.i("返回查询数据库结果", "nihao123"+msg.what);
if (msg.what > 0) {
j = 1;
} else {
j = 0;
}
Log.i("返回查询数据库结果", "i"+msg.what);
}
};
Log.i("返回查询数据库结果", "nihao"+j);
return j;
}
为什么我取的返回值始终是0? 展开
1个回答
展开全部
这个谷歌早已经给你实现了,使用handler:
例如在主线程创建handler
子线程发消息到这个handler
Handler handler=new Handler(){
@Override
public boolean handleMessage(Message msg){
switch (msg.what){
case 1:
//TODO
break;
}
}
//子线程里
Message msg = new Message();
msg.what = 1;
msg.object=XX;//传对象,还有arg1、arg2……
handler.sendMessage(msg);
例如在主线程创建handler
子线程发消息到这个handler
Handler handler=new Handler(){
@Override
public boolean handleMessage(Message msg){
switch (msg.what){
case 1:
//TODO
break;
}
}
//子线程里
Message msg = new Message();
msg.what = 1;
msg.object=XX;//传对象,还有arg1、arg2……
handler.sendMessage(msg);
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |