2016-03-02 144 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()