TWOcvfan
TWOcvfan

Reputation: 398

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.

Upvotes: 0

Views: 2092

Answers (3)

ישו אוהב אותך
ישו אוהב אותך

Reputation: 29794

If you're trying to do it in a method of the Activity subclass, then do the following:

url = new URL(getString(R.string.url2));

Or you can try using getResources()

From https://stackoverflow.com/a/5888219/4758255

Another related link for using url in string:

  1. URL in String resource xml
  2. How to properly reference the Strings.xml file, android
  3. Android: How store url in string.xml resource file?
  4. How to put the url on string.xml in android?

Upvotes: 0

Dharmbir Singh
Dharmbir Singh

Reputation: 17535

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.

Upvotes: 3

rams
rams

Reputation: 1580

xml code <string name="kms">KMs:</string>

You can get the string by using this

String name=getResources().getString(R.string.kms);

Upvotes: 0

Related Questions