hychoi99
hychoi99

Reputation: 23

Android - The method setText() is changing text of a widget even though it is never called

I have a basic block of code here with simple data passing between activities. Basically when there is data received, change the text of the button:

Bundle intentData = getIntent().getExtras();     
if (intentData != null) {
    String passedMsg = intentData.getString("userMsg");
    Button mainButton = (Button) findViewById(R.id.main_button);
    mainButton.setText(passedMsg);
} 

However, even on cases when the if conditional fails, the text of the button still changes. When I comment out the line mainButton.setText(passedMsg);, the text of the button remains unchanged.

It seems as though the presence of setText() alters the button's text regardless of whether that line of code is reached. Why does it do this?

Upvotes: 2

Views: 105

Answers (3)

hychoi99
hychoi99

Reputation: 23

It seems that the intentData isn't ever passed null and so the if statements don't fail

Upvotes: 0

Constantin
Constantin

Reputation: 1506

Obviously, your block of code is being executed multiple times. to prove this, do something like

static boolean initialized = false;

public void enteredBlockOfCode() {
     if(!initialized) {

            // code here only runs once ...

        initialized = true;
    }
}

Upvotes: 2

Yon Kornilov
Yon Kornilov

Reputation: 101

Either the condition you're checking is not the one you should be checking, or in the code you've compiled the if statement is immediately followed by a semicolon before the braces.

Upvotes: 0

Related Questions