java - 单击按钮后管理 mysql 连接

标签 java android mysql multithreading android-asynctask

我的目标是插入到某个 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执行完成时,使用AsyncTaskonPostExecute来更新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/

相关文章:

java - WSO2 - 尝试保存代理服务或序列时出现问题

java - Scala/Java 中的简单、无忧、零样板序列化,类似于 Python 的 Pickle?

android - 递归调用 getWritableDatabase

php - Yii 中 findBySQL 的结果

mysql - Highcharts动态更新饼图mysql

java - Maven 上的项目未导入其依赖项

java - 将方法应用于流

android - AutoCompleteTextView 检测用户是否选择了建议

android - ScrollView 中的线性布局不占据全高

mysql - 优化 MySQL GROUP BY/ORDER BY 计算集合交集