TWOcvfan TWOcvfan - 25 days ago 10
Java Question

getting info from string.xml in android studio does not work

I have written this line in mainActivity.java:

String url = getString(R.string.url2);


and ind strings.xml it looks like this:

<string name="url2">https://someurl.com/index.html</string>


but I get an error and if I write it like this in mainActivity.java

String url = "https://someurl.com/index.html";


then it works fine, but I need it to be in strings.xml for it to be easy to change.

How do I make it work?

EDIT: I have tried these:

String url = this.getString(R.string.url2);
String url = getResources().getString(R.string.url2);


and they do not work. The error I is that it does not get the url, simply said R.string.url2 does not lead to my url in strings.

Update: I have found the error, I had written it like this:

public class MainActivity extends ListActivity {

String url = this.getString(R.string.url2);

@Override
protected void onCreate(Bundle savedInstanceState) {


but I should have written it like this:

public class MainActivity extends ListActivity {

String url;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
url = this.getString(R.string.url2);


Thank you to those of you who tried to help with my problem.

Answer

Seems your code should work if it is not working then please try like this

Trick 1

String url = getResources().getString(R.string.url2);

Trick 2

this.getString(R.string.url2)

Hope it will help you.

Comments