Search code examples
androidstringandroid-resourcesfinalcharsequence

How to use a string id from res/values/strings.xml instead of String or CharSequence?


If I have this piece of code with hardcoded String "New event of importance":

public class MainActivity extends Activity {
    private NotificationManager mNManager;
    private static final int NOTIFY_ID = 1100;

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

        String ns = Context.NOTIFICATION_SERVICE;
        mNManager = (NotificationManager) getSystemService(ns);
        final Notification msg = new Notification(R.drawable.ic_launcher,
                "New event of importance",
                System.currentTimeMillis());

But would like to move it into res/values/string.xml file instead:

<string name="new_event">New event of importance</string>

Then how to use the R.strings.new_event in the above constructor (and yes I know that the constructor is deprecated)?

And one more question please - why is final keyword used above?


Solution

  • Activity has getString method that takes a string's id as parameter.

    Change

      "New event of importance"
    

    with

     getString(R.string.new_event);
    

    In general to access resources, you need a context object