Android: How store url in string.xml resource file

2019-01-22 20:17发布

I'm trying to store a fully qualified url, with also query params:

www.miosito.net?prova&reg=bis

but it's causing a problem because &reg is similar to ® entity and android tell me that and html entity is not well written.

I need this because every locale uses a fully different set of url query param.

I tried with [[CDATA[.. ]] but this syntax disliked by xml parser.

4条回答
smile是对你的礼貌
2楼-- · 2019-01-22 20:42

The problem is not with &req but with & itself. For XML/HTML you would have to use & entity (or &), but for URLs you should rather URL-encode (see docs) strings, and in that case said & should be replaced with %26. So your final string should look like:

www.miosito.net?prova%26reg=bis

查看更多
Deceive 欺骗
3楼-- · 2019-01-22 20:43

Percent encoding may do the trick: http://en.wikipedia.org/wiki/Percent-encoding You'll basically have something like this: www.miosito.net?prova%26reg=bis

查看更多
Summer. ? 凉城
4楼-- · 2019-01-22 20:50

You can enclose your url in double quotes, something like :

<string name="my_url">"www.miosito.net?prova&reg=bis"</string>

This is a recommended way to enclose string resources in Android.

Update 1 : Have a look at the following link for more info :

http://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling

Update 2: @WebnetMobile.com : Correct, indeed :) '&' is being treated a special character by xml and enclosing in quotes doesn't work. I tried out
www.miosito.net?prova%26reg=bis

and it didn't work out either. I even tried enclosing it in quotes but still didn't work. Am I missing something ?
Meanwhile, the following does work :

<string name="my_url">www.miosito.net%1$sprova%2$sreg=bis</string>

and then in code :

Resources resources=getResources();
String url=String.format(resources.getString(R.string.my_url),"?","&") ;

The '%1$s' and '%2$s' are format specifiers, much like what is used in printf in C. '%1$s' is for strings, '%2$d' is for decimal numbers and so on.

查看更多
贼婆χ
5楼-- · 2019-01-22 20:52

Store it like this:

<string name="my_url">"www.miosito.net?prova&amp;reg=bis"</string>

Where &amp; is the XML equivelant of the ampersand symbol &.

查看更多
登录 后发表回答