Android读写配置2
上篇文章采用 Properties 读写配置,各种路径错误,要么没有写入权限.
后来查资料,采用另一种方式读写 SharedPreferencesImpl
直接贴代码
公共类 -- 读写
package com.**.demo.utils; import android.content.Context; import android.content.SharedPreferences; import android.util.Log; public class UrlConfig { private static SharedPreferences share; private static String configPath = "appConfig"; public static SharedPreferences getProperties(Context context) { try { share = context.getSharedPreferences(configPath, Context.MODE_PRIVATE); } catch (Exception e) { e.printStackTrace(); } return share; } public static String setProperties(Context context, String keyName, String keyValue) { try { share = context.getSharedPreferences(configPath, Context.MODE_PRIVATE); SharedPreferences.Editor editor = share.edit();//取得编辑器 editor.putString(keyName, keyValue);//存储配置 参数1 是key 参数2 是值 editor.commit();//提交刷新数据 } catch (Exception e) { e.printStackTrace(); Log.e("setPropertiesError", e.toString()); return "修改配置文件失败!"; } return "设置成功"; } }
封装
package com.**.demo.json; import android.content.Context; import android.content.SharedPreferences; import com.**.demo.utils.UrlConfig; /** * 网络请求 */ public class UrlString { private static final String IP = "192.168.1.10:8000"; private String contrastIPName = "contrastIP"; // 上传路径 private String ip; private String ipAddress; public void setIPAddress(Context context) { //Properties proper = ProperTies.getProperties(context); //this.ip = proper.getProperty(contrastIPName, ""); SharedPreferences proper = UrlConfig.getProperties(context); this.ip = proper.getString(contrastIPName, ""); // 设置默认值 if (this.ip.equals("")){ this.ip = IP; } this.ipAddress = "http://" + this.ip + "/v1.0/index.html"; } public String setIPAddress(Context context, String keyValue) { // String result = ProperTies.setProperties(context, contrastIPName, keyValue); String result = UrlConfig.setProperties(context, contrastIPName, keyValue); this.ip = keyValue; this.ipAddress = "http://" + this.ip + "/v1.0/index.html"; return result; } public String getIP() { return this.ip; } public String getIPAddress() { return this.ipAddress; } }
使用方式同上一篇.
参考: http://www.jianshu.com/p/87024ce283c9
参考: http://leequer.iteye.com/blog/654942