joon
joon

Reputation: 1

Boolean value assigned is never used - Java / Android Studio

I don't understand why Android Studio is telling me that the value assigned to isOne is never being used. I have set the value to be false and true within the if statement of the fade method. When I declare the variable isOne as a member variable instead of a local variable, however, the error is gone and it seems to work perfectly. I'm not sure why that fixed the error....Any thoughts ?

private ImageView img1;
private ImageView img2;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    img1 = (ImageView) findViewById(R.id.porsche1);
    img2 = (ImageView) findViewById(R.id.porsche2);

    img1.setOnClickListener(this);
    img2.setOnClickListener(this);

}

@Override
public void onClick(View v) {
    fade();
}

public void fade(){
   boolean isOne = true;

    if (isOne) {
        img1.animate().alpha(0).setDuration(2000);
        img2.animate().alpha(1).setDuration(2000);
        isOne = false;
    } else {
        img1.animate().alpha(1).setDuration(2000);
        img2.animate().alpha(0).setDuration(2000);
        isOne = true;
    }

}

}

Upvotes: 0

Views: 1216

Answers (2)

Dnyaneshwar Panchal
Dnyaneshwar Panchal

Reputation: 444

Use this way, I hope it will help for you

boolean isOne = false;   // Use Globally

    public void fade(){

        if (isOne) {
            img1.animate().alpha(0).setDuration(2000);
            img2.animate().alpha(1).setDuration(2000);   
        } else {
            img1.animate().alpha(1).setDuration(2000);
            img2.animate().alpha(0).setDuration(2000);
        }
    }

Upvotes: 1

yshavit
yshavit

Reputation: 43391

At the end of both the "if" and "else" blocks, you assign a value to isOne. You never use that value after setting it, so those assignments are unused. Each new invocation redeclares isOne, so that last assignment does not become the next invocation's initial value.

Fields are harder to analyze, since the last assignment of one invocation would be used as the initial value of the next invocation (assuming there two methods are invoked on the same instance).

Upvotes: 0

Related Questions