zoukankan      html  css  js  c++  java
  • Android SharedPreferences 见解

    今天突然遇到了SharedPreferences问题,虽然以前用过,但从没有深入的了解一下,今天就顺便深入了解一下,并总结一下,防止以后忘记。

    SharePreferences是Android平台上一个轻量级的存储类,特别适合用于保存软件配置参数。比如boolean,float,long ,int,String的数据,使用SharedPreferences保存数据,其实质是采用xml文件存放数据,存放的路径为:/data/data/<包名>/shared_prefs.

    而获取的SharedPreferences的方式有两种:

    1、调用Context对象的getSharePreferences()方法

    2、调用Activity对象的getPreferences()方法

    区别:

    调用Context对象的getSharedPreferences()方法获得的SharedPreferences对象可以被同一个应用程序下的其他组件共享,

    调用Activity对象的getPreferences()方法获得的SharedPreferences对象只能在当前Activity中使用。

    SharedPreferences有四种模式:

    Context.MODE_PRIVATE
    Context.MODE_APPEND
    Context.MODE_WORLD_READABLE
    Context.MODE_WORLD_WRITEABLE

    Context.MODE_PRIVATE:是默认模式,表示该文件是私有数据,只能本应用程序才能访问,在该模式下,不存在文件就创建一个,存在的话,写入的新内容会覆盖原文件内容。

    Context.MODE_APPEND:该模式下检查文件是否存在,存在就追加内容。否则就创建新文件。

    Context.MODE_WORLD_READABLE  和  Context.MODE_WORLD_WRITEABLE是用来控制其他应用程序是否有权读写该文件。

    Context.MODE_WORLD_READABLE  表示当前文件可以被其他应用程序读取。  

    Context.MODE_WORLD_WRITEABLE:表示当前文件可以被其他应用写入。

    保存方法:

    SharedPreferences preferences = getSharedpreferences("student",Context.MODE_PRIVATE);

    Editor editor = preferences.edit();

    editor.putString("name","张三");

    editor.putString("age","22");

    editor.commit();

    获取SharedPreferences:

    SharedPreferences preferences = getSharedPreferences("student",Context.MODE_PRIVATE);

    String name = preferences.getString("name","默认姓名");

    String age = preferences.getString("age","0");

  • 相关阅读:
    0/1背包问题
    假如爱有天意(中文版)
    tomcat集群
    分布式锁
    centos7安装Harbor(转载)
    isEmpty和isBlank的区别
    单体应用架构和分布式架构的比较
    微服务鉴权
    mysql的时区设置
    RSA非对称加密算法
  • 原文地址:https://www.cnblogs.com/Jett/p/3817161.html
Copyright © 2011-2022 走看看