我的目标是插入到某个 db 2 值、id 和 pass。 我有一个注册页面,要求提供该数据和一个完成操作的按钮。 那么在按钮监听器上我应该做什么?很多人告诉我使用AsyncTask(我不知道如何使用)而不是Thread。 请记住,此类需要获取 2 个参数 id 并传递.. 据我所知,线程在使用调用 run 方法的 start() 方法后启动,而 run 方法没有参数.. 那么我如何传递这些参数2个参数? 无论如何我很困惑。 另一件事是,如果我在 catch block 上遇到任何类型的错误,我会将错误放在某个字符串上,例如: String error = exceptionInstance.toString();然后我可以从注册页面查看该字符串并打印错误。
myThreadInstance.start(); textViewInstance.setText(myThreadInstance.getError());
这是一场马拉松......我很困惑!!!!!!
最佳答案
据我使用 AsyncTask而不是 Thread
因为它易于使用,并且您可以更好地控制后台线程,而无需执行额外的代码来创建单独的逻辑以在线程执行完成时更新 Ui,计算进度单位以便用户花费多少时间通过要完成的操作等
您的第一问题如何在单击按钮时将用户名
和密码
发送到AsyncTask
。用于此用途AsyncTask
构造函数为:
LoginOperation loginopertion=new LoginOperation(strusername, strpassword);
loginopertion.execute("");
您的第二回答我们如何在AsyncTask
中接收用户名
和密码
并在任务完成时更新Ui当doInBackground
执行完成时,使用AsyncTask
的onPostExecute
来更新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
关于java - 单击按钮后管理 mysql 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13978370/