Search code examples
androidstringoncreategetstring

Best way to use getString()


I'm having some problems on where and how to place and call the getString().

I tried at the beginning of my activity where I usually define it but always get an error. Should it be only after onCreate()?

Some of my strings I use it very often so I don't want to use getString() every time I use them.

Is this the correct way?

private String helloWorld = getString(R.string.hello_world);

Thank you very much! :)


Solution

  • at the top of your file do:

    private String helloWorld;
    

    And then, in onCreate(),

    do:

    helloWorld = getString(R.String.hello_world).
    

    The problem is that getString needs a reference to the activity context, which has not been associated with your class until onCreate is called.