Android 共享参数 SharedPreferences
程序员文章站
2023-10-29 11:51:10
完成共享参数的读写public class SharedPreference { private Context context; public SharedPreference(Context context) { // TODO Auto-generated constructor stub t... ......
完成共享参数的读写
public class sharedpreference { private context context; public sharedpreference(context context) { // todo auto-generated constructor stub this.context = context; } public boolean savemessage(string name, string passwd) { boolean flag = false; // 自动保存成 userinfo.xml sharedpreferences sharedpreferences = context.getsharedpreferences("userinfo", context.mode_private); // 对数据进行编辑 sharedpreferences.editor editor = sharedpreferences.edit(); editor.putstring("name", name); editor.putstring("passwd", passwd); // 将数据持久化到存储介质中 flag = editor.commit(); return flag; } public map<string, object> getmessage() { map<string, object> map = new hashmap<string, object>(); sharedpreferences sharedpreferences = context.getsharedpreferences("userinfo", context.mode_private); string name = sharedpreferences.getstring("name", ""); string passwd = sharedpreferences.getstring("passwd", ""); map.put("name", name); map.put("passwd", passwd); return map; } }
编写测试函数
private button button1; private button button2; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); button1 = (button) findviewbyid(r.id.button1); button1.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { // todo auto-generated method stub sharedpreference sharedpreference = new sharedpreference(mainactivity.this); boolean flag = sharedpreference.savemessage("furong", "123456"); toast.maketext(mainactivity.this, "---->" + flag, 1).show(); } }); button2 = (button) findviewbyid(r.id.button2); button2.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { // todo auto-generated method stub map<string, object> map; sharedpreference sharedpreference = new sharedpreference(mainactivity.this); map = sharedpreference.getmessage(); toast.maketext(mainactivity.this, map.tostring(), 1).show(); } }); }
写测试
读测试
推荐阅读
-
Android 共享参数 SharedPreferences
-
Android SharedPreferences四种操作模式使用详解
-
Android SharedPreferences实现记住密码和自动登录
-
Android SharedPreferences实现保存登录数据功能
-
Android开发中4个常用的工具类【Toast、SharedPreferences、网络及屏幕操作】
-
10.Android-SharedPreferences使用
-
android中SharedPreferences实现存储用户名功能
-
Android中的SQL查询语句LIKE绑定参数问题解决办法(sqlite数据库)
-
Android通过SharedPreferences实现自动登录记住用户名和密码功能
-
Android 存储SharedPreferences出现无法获取到数据