我的目标是插入某个db 2值,id和pass。 我有一个注册页面,要求提供该数据和一个按钮来完成操作。 所以在按钮监听器上我该怎么办?很多人告诉我使用AsyncTask(我不知道要使用)而不是Thread。 请记住,这个类需要获取2个参数id并传递..并且据我所知,线程在使用调用run方法的start()方法后启动,并且run方法没有参数..所以我怎么能传递那些2个参数? 无论如何,我很困惑。 另一件事是,如果我在catch块上遇到任何类型的错误,我会将错误放在某个字符串上,如:String error = exceptionInstance.toString();然后我可以从注册页面看到该字符串并打印错误。
myThreadInstance.start(); textViewInstance.setText(myThreadInstance.getError());
这是某种马拉松......我很困惑!!!!!!!
答案 0 :(得分:1)
根据我使用AsyncTask而不是Thread
,因为它易于使用,并且您可以更好地控制后台线程,而无需执行额外的代码来创建用于在线程执行完成时更新Ui的单独逻辑,计算进度单位,以便用户通过操作完成等多少时间
您的第一次提问您如何在点击按钮时将username
和password
发送到AsyncTask
。为此使用AsyncTask
构造函数为:
LoginOperation loginopertion=new LoginOperation(strusername, strpassword);
loginopertion.execute("");
第二次回答我们如何在username
中收到password
和AsyncTask
,并在完成此任务的onPostExecute
AsyncTask
时更新Ui 1}}在doInBackground
执行完成时更新Ui,例如:
public class LoginOperation extends AsyncTask<String, Void, String> {
String strusername,strpassword;
public LoginOperation(String strusername, String strpassword){
this.strusername=strusername;
this.strpassword=strpassword;
}
@Override
protected void onPreExecute() {
//show progressbar here
}
@Override
protected String doInBackground(String... params) {
string result="";
try
{
result=="success or fail";
//do your network opertion here
}
catch(SQLException e)
{
result="ERROR";
}
return result;
}
@Override
protected void onPostExecute(String resultmsg) {
// show error here and update UI
//or other opertion if login success
textViewInstance.setText(resultmsg);
}
}
有关AsyncTask方法的更多信息,请参阅
http://developer.android.com/reference/android/os/AsyncTask.html