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

573 Views Asked by At

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?

4

There are 4 best solutions below

0
On BEST ANSWER

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

0
On

use this

String Name=getResources().getString(R.string.new_string)

and take a look to the docs here http://developer.android.com/guide/topics/resources/string-resource.html

0
On
String str = context.getResources().getString(R.string.your_string_id)
0
On

Create the new string in your strings.xml (or other resource file)

Then you can reference it in your code as:

Context context = getApplicationContext();
Resources res = context.getResources();
String newEvent = res.getString(R.string.new_event)