在用普通的方法同时保存用户名和密码时,中间必须要有一个分隔符来区分用户名和密码,比如用“##”作为分隔符,此时会导致一个问题,如果用户名或者密码中也包含“##”,则重新读取用户名和密码时就会出错。

用SharedPreferences保存文件的方法就可以解决这个问题:

Context context=new Context();

SharedPreferences  sp=

context.getSharedPreferences(“config”,context.MODE_PRIVATE);//config为文件名,此时并不会创建文件,只有在执行putString()方法后文件才会被创建。

Editor editor=sp.edit();//获取SharedPreferences编辑器

editor.puString(“username”,username);

editor.puString(“password”, password);

editor.commit();

代码运行后会自动在程序包内创建一个名为“shard_prefs”的文件夹,我们保存的信息就在该文件夹内的“config.xml”文件内。

比如我们保存的password为afafgg232,username为afa.则文件内容如下:


SharedPreferences保存的文件重新读取出来也很方便:

SharedPreferences  sp=

getSharedPreferences(“config”,MODE_PRIVATE);

String username=sp.getString(“username”,””);

//getString(name,defValue)的第二个参数为当读取的文件中不存在第一个参数name的时候,为name赋的值。这里设的空。

String password=sp.getString(“password”,””);

SharedPreferences常用来保存程序的配置信息,比如保存用户对软件的设置信息。手机系统里的设置信息就是用这种方法保存的。

更多相关文章

  1. Android烧录镜像文件介绍
  2. android崩溃日志保存sdcard打开并发送到email
  3. 如何解决:ERROR: the user data image is used by another emulat
  4. Android中运行的错误:java.lang.UnsatisfiedLinkError: Couldn't
  5. Android中资源文件中的字符串数组string-array
  6. Android(安卓)Studio 常用功能介绍
  7. Android(安卓)data分区格式F2FS改为EXT4
  8. 关于Android多渠道打包
  9. Android项目构建之build.gradle配置与打包

随机推荐

  1. css之flex容器
  2. 3.24实例演示flex容器中的四个属性的功能
  3. 传统定位和flex定位
  4. css-flex布局
  5. 【CSS入门】理解css中min-width和max-wid
  6. 210323 CSS 盒子模型 字体图标 定位
  7. 万岳教育直播源码,教育app源码,教育系统
  8. 固定定位:模态框
  9. 苹果Mac强大的思维导图工具:SimpleMind
  10. 如何选择好的运维服务商?