简体   繁体   中英

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.

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.

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

You can get the string by using this

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

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM