Question

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 = "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.

Was it helpful?

Solution

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top