-1

When I get the string from the strings.xml , I don't get an error right away, but I can't run the program :

String myButtonText = getString(R.string.ButtonText);

(when I remove this line and this variable from my program it works perfectly)

I'll put up my program, in case you'd need it:

public class MainActivity extends AppCompatActivity {

    private Button button;
    String myButtonText = getString(R.string.ButtonText);

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

        button = (Button) findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

           if(myButtonText.equals("Red")){//the button's text is "red" already
               button.setText("Blue");
           }
            }//I'm changing the text on the button to "blue" when it says"red"
        });
    }
}
ThomasW
  • 16,981
  • 4
  • 79
  • 106
  • remove the attribution from the top of the class and do this inside the onCreate method: `myButtonText = getResources().getString(R.string.ButtonText)` – joao86 Sep 14 '17 at 00:42

2 Answers2

1

You are doing:

String myButtonText = getString(R.string.ButtonText);

I think you have to retrieve value from strings.xml inside onCreate() method:

String myButtonText = getResources().getString(R.string.ButtonText);
Satan Pandeya
  • 3,747
  • 4
  • 27
  • 53
1

You should call getString(...) within the activity lifecycle to ensure that all the components under the hood are initialized.

In your example, you should call myButtonText = getString(R.string.ButtonText); in onCreate(...)

Jon
  • 1,715
  • 12
  • 14