开发者

Android: how to put parameters in configuration files

开发者 https://www.devze.com 2023-02-19 06:01 出处:网络
I need to parametrize my app by adding, for example, the URL of a web service to be called. In other environments I would use a .ini file or a web.config file开发者_开发百科 to store the info. How can

I need to parametrize my app by adding, for example, the URL of a web service to be called. In other environments I would use a .ini file or a web.config file开发者_开发百科 to store the info. How can this be achieved in Android?


For android you can store settings in a number of ways. The simplest is SharedPreferences. You could also store the values in a sqlite database or use a ContentProvider.

To retrieve preferences, you do something like below.

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String myURL = prefs.getString("url",defaultURL);

You can then set these from a PreferenceActivity with some defaults provided in the XML that stores your preferences.


You can store the value in res/values/strings.xml as <string name="serviceUrl">http://www.example.com</string>and pull it out in your activity using getResources().getString(R.string.serviceUrl)

This is not suitable for values which can be modified by the user. You should use the PreferenceManager in that case.


could you store the details in an xml file and read them in ? or possibly SharedPreferences ? or an SQLITE database ?


There could be 2 possible ways.

  1. Create a system.properties file which is a simple text file and put all your configurations in that. Once done, put that file in asset folder and access it in your activity by using AssetManager.

  2. Create a final class say Data.java and put all properties in that and access the properties in static way through out the application.

I recommend to go for option 2.

0

精彩评论

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