开发者

What is the best way to externalize URL's?

I have 10 URL's in my application, that are currently hard-coded. I want to externalize this and put it in a file so that my application can read it in.

What is the best way of doing this?

private String appURL 开发者_StackOverflow中文版= "http://..."
private String storeURL = "http://..."
private String someURL = "http://..."

Note: I will never be writing out to this file in my app. I want the developer to be able to open up the file, and change the URL if necessary.


Easiest way to externalize strings in an android application is to use string resources. Create file uris.xml at res/values folder:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="appUrl">http://...</string>
    <string name="storeUrl">http://...</string>
    <!-- etc /-->
</resources>

You then can then access the strings by:

String appUrl = getString(R.string.appUrl);
String storeUrl = getString(R.string.storeUrl);
//..etc

getString() is a method of Context class. Also keep in mind that you should wait until a Context will be initialized before starting access its resources. Hence invoke getString() not earlier then at onCreate() method of Activity or Application.


You can put the values in a XML "configuration" file, then just read the values from the XML file.

Example of reading an XML file.

Or just use Android's native res folder XML resources files as pointed out by Konstantin Burov.


If you want ability to have external flat file to be editable you can simply create a text file on say SD (and have some defaults as static strings or properties). Then your code reads the file (standard Java IO) and pics the changes say in onCreate of your Activity

You can also have such file in /assets folder; see this for example

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜