Reputation: 398
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
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:
Upvotes: 0
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
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