【发布时间】:2014-08-29 11:38:12
【问题描述】:
我正在开发一个 android 应用程序,我可能需要更改几个变量,但不想重新编译并将 android 应用程序部署到 android 智能手机中。
在 java 中,我会像之前在 java 中所做的那样做一个属性加载器:
public class PropertyLoader {
private static Properties props = null;
/**
* Method initializes the PropertyLoader by reading all configuration settings
* from the RememberMeServer.conf file.
*/
public static void initializeProperties() {
String propFile = getCatalinaDirectory() + "RememberMeServer.conf";
System.out.println(propFile);
File configFile = new File(propFile);
InputStream inputStream = null;
try {
inputStream = new FileInputStream(configFile);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
props = new Properties();
try {
props.load(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Returns a string value from the configuration file.
*
* @param key a string which represents the key of the requested value in the configuration file
* @return the value of the requested key from the property file as a string or null if the
* requested key could not be found.
*/
public static String getStringValue(String key) {
return props == null ? null : props.getProperty(key);
}
/**
* Returns an int value from the configuration file.
*
* @param key a string which represents the key of the requested value in the configuration file
* @return the value of the requested key from the property file as an int or null if the
* requested key could not be found.
*/
public static Integer getIntValue(String key) {
return props == null ? null : Integer.valueOf(props.getProperty(key));
}
/**
* Returns the directory of the project�s workspace as a string
*
* @return Returns the directory of the project�s workspace as a string
*/
public static String getWorkspaceDirectory() {
URL url = PropertyLoader.class.getClassLoader().getResource(
"hibernate.cfg.xml");
return url.getFile().substring(0,
url.getFile().lastIndexOf("hibernate.cfg.xml"));
}
/**
* Returns the directory of the servlet container catalina directory as a string
*
* @return Returns the directory of the servlet container catalina directory as a string
*/
public static String getCatalinaDirectory() {
String workspace = getWorkspaceDirectory();
return workspace
.substring(0, workspace.lastIndexOf("RememberMeServer"));
}
}
虽然在 android 中有一个叫做 SharedPreferences 的东西,我已经在我的应用程序中使用了它。虽然我从不使用 SharedPreferences 直接在文件中更改变量信息,但只能从应用程序的代码中更改。
Android 应用程序中的最佳替代方案是什么?
因为我想要实现的是,对我来说,更好地由属性加载器表示,它可以保存我不想在我的 java 代码中硬编码的东西。
【问题讨论】:
-
您是要保存变量状态还是将文件保存到设备? Android 为这两者提供了内置解决方案。
-
我想存储对应用程序运行至关重要的静态信息,但它不会以编程方式添加或删除变量。那些是什么?
-
SharedPreferences 将满足您的需求。我只想阅读更多关于文档的内容。如果这不符合您的需求,不妨看看 Parse SDK,看看它是否适合您。
-
我使用并理解 SharedPreferences。但我想更改文件中的变量。所以我可以更改 ips 和端口之类的东西,应用程序将使用它们来执行与服务器的通信
-
甚至共享首选项都存储在文件中,因此您实际上可以像属性文件一样每次替换文件
标签: java android sharedpreferences properties-file