2016-12-15 7 views
-3

アプリケーションを減算して閉じるようにカウンタを設定するとエラーが発生します。 「最終変数カウンタに値を代入できません」というエラーが表示されます。成功していないユーザーが3回ログインすると、アプリケーションが終了します。アンドロイドスタジオでカウンタを追加してアプリケーションを終了する方法

 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?が役に立ちます。

編集:

他の部分でやっていることは意味がありません。これらからgetText()を使用したuserTextpassTextのテキストを設定しています。次に、これらの同じ値を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(); 
        } 
       } 
関連する問題