Ian Sonic Ian Sonic - 10 months ago 59
Android Question

How to access string resource in android of text in AlertDialog

I am asking this question even though there are possible duplicates but those didn't worked for me.

I am trying to access to


in AlertDialog but I can't seem to make it. I have said


in the following code below but it didn't worked and gave out an error.
Is there any possible ways to get strings from AlertDialog or is it impossible?

Code below.

This is AlertMainActivity.java

AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("Add a New Task") //AlertTitle
.setMessage("What do you want to do next?") //AlertMessage
.setPositiveButton("Add", new DialogInterface.OnClickListener() //Add {
.setNegativeButton("Cancel", null) //Cancel

and strings.xml

<string name="AlertTitle">Add a New Task</string>
<string name="AlertMessage">What do you want to do next?</string>
<string name="Add">Add</string>
<string name="Cancel">Cancel</string>


Answer Source

When using String resources programmatically you should use


instead of


Also for this particular case there are two methods for setting the Title. Either trough the resource id, which would be R.string.AlertTitle or by setting a String, which can get from getString()


see Android: How do I get string from resources using its name? for more information. You can do getString instead of getResources().getString(...) when using it from an Activity or Fragment