Android AsyncTask 和登录

Posted

技术标签:

【中文标题】Android AsyncTask 和登录【英文标题】:Android AsyncTask and Login 【发布时间】:2015-05-13 00:02:18 【问题描述】:

我正在编写一个 android 登录页面,并且我使用了一个扩展 AsyncTask 的类。

问题是我似乎无法“控制”异步任务的流程。

如果我插入正确的用户名和密码,如果我在连接到数据库时单击一次,则表示它们不正确,但如果我再次按下它就可以了。

幸运的是,当我输入错误的用户名或密码时,它不会发生。

我使用了一个布尔变量来显示密码和用户名是否正确。

 public class LoginPage extends Activity implements OnClickListener 
 public boolean loginCorrect=false;
 //other code
 

然后我实现了 OnClick(View v) 功能:

 public void onClick(View v)
 //switch related code
    case(R.id.btn_submit):
    connectToDB(v);
if(loginCorrect)
loginCorrect=false // If i have to login another time, it will make all the needed checks 
Intent intent = new Intent(this, MainPage.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);  
finish();
startActivity(intent);   

    else
Toast.makeText(getApplicationContext(),"Email or password is incorrect", 
        Toast.LENGTH_SHORT).show();



break;
//other code

在connectToDb(v)中:

   public void connectToDB(View view)
   
  ConnectAsync task = new ConnectAsync();
   task.execute();

     

在doInBackground中

        @Override
        protected String doInBackground(String... urls) 

            String url= //jdbc string
            String user=insUser.getText().toString();
            String password=insPw.getText().toString();
            Connection connessione=null;
            Statement statement=null;
            ResultSet resultSet=null;
            String sql=//sql query
            try        Class.forName //driver loading
            connessione=DriverManager.getConnection(url,user,password);
                statement=connessione.createStatement();
                resultSet=statement.executeQuery(sql);
                if(resultSet.next())
                    if( //i found a tuple with that username and   that  password
                    

                        loginCorrect=true;
                    
                connessione.close();

            
            catch (SQLException se)
                //exception related code
            
            catch (ClassNotFoundException cnfe) 
                //exception related code
            


       return null;
        

【问题讨论】:

See here你需要等待任务完成才能检查值 【参考方案1】:

问题在于,根据定义,AsyncTask 不会在 UI 线程上运行。所以通过这样做:

connectToDB(v);
if(loginCorrect)

您不会等待AsyncTask 的结尾来检查该值。我建议您实现AsyncTaskonPostExecute 方法,该方法将在AsyncTask 结束后在UI 线程上调用。 像这样的:

@Override
protected void onPostExecute(YOUR_TYPE result) 
if(loginCorrect)
loginCorrect=false // If i have to login another time, it will make all the needed checks 
Intent intent = new Intent(this, MainPage.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);  
finish();
startActivity(intent);   

    else
Toast.makeText(getApplicationContext(),"Email or password is incorrect", 
        Toast.LENGTH_SHORT).show();




【讨论】:

成功了。我发现你回答最直观的一个。所以,答案被接受了。【参考方案2】:

首先,您需要覆盖 AsyncTask 的 onPostExecute 函数,该函数将 处理您的查询结果。您可以从 Activity 中调用函数,也可以在 onPostExecute 中添加代码。

class ConnectToDBTask extends AsyncTask<Void,Void,Boolean>
  
    @Override
    protected Boolean doInBackground(Void... params)
    
      Boolean bResult = false;
      try
      
        bResult = true;
      
      catch (Exception se)
      
      


      return bResult;

    

    @Override
    protected void onPostExecute(Boolean aBoolean)
    
      if ( aBoolean == true)
      
        Main.this.HandleLoginResult(aBoolean);
      
      super.onPostExecute(aBoolean);
    

  

然后您可以在您的活动中添加一个函数,如果登录成功,该函数将调用该意图。

public void HandleLoginResult(Boolean bResult)
  
    if ( bResult == true)
    
      Intent intent = new Intent(this, Main.class);
      intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
      intent.putExtra("EXIT", true);
      finish();
      startActivity(intent);
    
  

【讨论】:

【参考方案3】:

在异步任务完成之前,您永远不会检查用户是否再次按下按钮。您可以设置 btn_submit.setClickable(false) ,然后在您的任务完成时将其设置回 true。只需覆盖onPostExecute(...) 并在里面插入btn_submit.setCLickable(true)。 有什么问题吗?

【讨论】:

为 setClickable 函数加一个。不错!

以上是关于Android AsyncTask 和登录的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Android Studio 的登录活动模板中实现 AsyncTask

AsyncTask Android - 设计模式和返回值

如何在android的Asynctask中显示json响应[重复]

android中AsyncTask中的ProgressDialog

Facebook 登录 AsyncTask #4 NullPointerException 启动时崩溃

使用 Kotlin 显示来自 AsyncTask 的 Toast 消息