2016-12-15 54 views
-3

當設置計數器以減去並關閉應用程序時,出現錯誤。我收到一個錯誤「無法將值賦給最終變量計數器」。如果用戶登錄3次而沒有成功退出應用程序。如何在android studio中添加計數器以退出應用程序

 final int counter = 3; 

     //Set the OKButton to accept onClick 
     OKButton.setOnClickListener(new View.OnClickListener() { 
      @Override 

      //once onClick is initalized it takes user to page menu 
      public void onClick(View v) { 

       //display text that was inputed for userText and passText 
       user = userText.getText().toString(); 
       pass = passText.getText().toString(); 

       //create if loop which checks if user and pass equals the credentials 
       if (user.equals("pshivam") && pass.equals("Bway.857661")) { 

        //display toast access welcome 
        String welcome = "Access Granted."; 

        //Create a Toast to display the welcome string in the MainActivity. 
        Toast.makeText(MainActivity.this, welcome, Toast.LENGTH_SHORT).show(); 
        setContentView(R.layout.account_main); 
       } 
       //create else if loop which checks if user or pass does not equals the credentials 
       else if (!user.equals("pshivam") || !pass.equals("Bway.857661")){ 

        //displays previous entry 
        userText.setText(user); 
        passText.setText(pass); 

        //allows user to re-enter credentials. 
        user = userText.getText().toString(); 
        pass = passText.getText().toString(); 


        //display toast access fail 
        String fail = "Access Denied! Please Try again."; 
        //Create a Toast to display the fail string in the MainActivity. 
        Toast.makeText(MainActivity.this, fail, Toast.LENGTH_SHORT).show(); 
        counter--; 
        if(counter == 0){ 
         finish(); 
        } 
       } 
      } 
     }); 
    } 
} 
+2

你不能改變最終變量的值 – uptoNoGood

+0

我該如何改變它?使用一個普通的int? –

+0

檢查我的答案 – uptoNoGood

回答

0

做這樣的事情:

OKButton.setOnClickListener(new View.OnClickListener() { 
      int counter = 3; 
      @Override 
      //once onClick is initalized it takes user to page menu 
      public void onClick(View v) { 

您也可以從裏面onClick調用一個函數,它會遞減變量,或使用你的類中聲明靜態字段

How to increment a Counter inside an OnClick View EventHow do I use onClickListener to count the number of times a button is pressed?可能會有所幫助。

編輯:

你在做的其他部分沒有任何意義。你正在設置文本userTextpassText,你剛剛從這些使用getText()。然後,您將這些相同的值存儲到userpass。但是,當您再次調用onClick時,您並未在任何地方使用這些變量,並且它們會得到新值。爲什麼不保持簡單:

   else { 

        //display toast access fail 
        String fail = "Access Denied! Please Try again."; 
        //Create a Toast to display the fail string in the MainActivity. 
        Toast.makeText(MainActivity.this, fail, Toast.LENGTH_SHORT).show(); 
        counter--; 
        if(counter == 0){ 
         finish(); 
        } 
       } 
相關問題