2016-03-02 113 views
0

因此,让我们说用户输入正确的凭证,他们点击按钮登录,我必须点击两次才能登录。我认为它是因为我在我的AsyncTask开头声明它,但我不确定。双击按钮登录AsyncTask?

我想如何工作:用户输入正确的凭证,他们点击按钮,AsyncTask调用我的服务器,并确保凭据是正确的,并将变量设置为false(所以我知道日志工作)然后活动开始。

的AsyncTask代码:

public class BackgroundTask extends AsyncTask <String,Void,String> { 
Context ctx; 

public static boolean LOGIN_FAILED = true; 

public static String Account; 

BackgroundTask(Context ctx){ 
    this.ctx = ctx; 
} 

@Override 
protected void onPreExecute() { 

} 


@Override 
protected String doInBackground(String... params) { 
//removed extra code here for the question. This is where i get result 
} 


@Override 
protected void onProgressUpdate(Void... values) { 
    super.onProgressUpdate(values); 
} 


@Override 
protected void onPostExecute(String result) { 

    if(result.equals("Login failed...")){ 
     //If there email or password didn't match up in the DB then they couldn't log in. 
     LOGIN_FAILED = true; 
    }else{ 
     LOGIN_FAILED = false; 

     if (result.equals("Welcome: Buyer")){ 
      Account = "Buyer"; 
     }else if(result.equals("Welcome: Seller")){ 
      Account = "Seller"; 
     } 
    } 
} 
} 

按钮的代码(我所说的按钮被点击时,此方法):

public void startActivity() { 
    //If the user gets the credentials right when they sign in then i start the activity. 
    if (BackgroundTask.LOGIN_FAILED == false) { 
     if (BackgroundTask.Account.equals("Buyer")) { 
      startActivity(new Intent(getApplicationContext(), BuyerHomePage.class)); 

     } else if (BackgroundTask.Account.equals("Seller")) { 

      startActivity(new Intent(getApplicationContext(), SellerHomePage.class)); 

     } 

    }else if(BackgroundTask.LOGIN_FAILED == true){ 

     //A TOAST shows up (because the user couldn't connect) saying they messed up there email or password. 
     Toast.makeText(SignInForm.this, "Email or password incorrect", Toast.LENGTH_SHORT).show(); 

    } 
} 

回答

0

在你点击链接你开始活动,但在你的描述你表示您打电话给服务器。哪一个是正确的?为什么在验证凭证之前,您会先点击按钮开始一项活动?

此外,假设您的服务进行异步调用以验证凭据,您不需要异步任务来调用它,服务应该立即从该活动的“验证凭据”调用中返回,并且一旦它已验证凭据,它应通过回调方法回调您的活动。

+0

对不起,当我点击按钮时,我打电话给我的服务器,并检查输入的电子邮件和密码是否与数据库中的电子邮件和密码相匹配。 – Lazar

+0

您可以分享您开始异步任务的代码吗? – Francesc

+0

我应该怎么做? – Lazar

1

根据你分享的代码,你没有任何地方叫你的AsyncTask。

假设:假设在startActivity()中调用异步。然后,如果您只要呼叫异步任务,您检查值BackgroundTask.LOGIN_FAILED

.... 这是错误的方法。异步会在后台进行,因此在任务完成之前,您的代码将对BackgroundTask.LOGIN_FAILED进行检查。 正确的做法是在完成时开始您的活动onPostExecute()