• android SharedPreferences


    MODE_PRIVATE,//默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容,如果想把新写入的内容追加到原文件中,可以使用Activity.MODE_APPEND  
    MODE_WORLD_READABLE,//表示当前文件可以被其他应用读取,
    MODE_WORLD_WRITEABLE,//表示当前文件可以被其他应用写入;
    //如果希望文件被其他应用读和写,可以传入:Activity.MODE_WORLD_READABLE+Activity.MODE_WORLD_WRITEABLE

    SharedPreferences preferences;
      SharedPreferences.Editor editor;
    preferences = getSharedPreferences("crazyit", MODE_WORLD_READABLE);
    //编辑

    editor.putString("time", sdf.format(new Date()));
    // 存入一个随机数
    editor.putInt("random", (int) (Math.random() * 100));
    // 提交所有存入的数据
    editor.commit();

    //读取

    1:存取数据的程序代码

    String time = preferences.getString("time", null);
    // 读取int类型的数据
    int randNum = preferences.getInt("random", 0);

    //读取不同程序的数据

    preferences = getSharedPreferences("count", MODE_WORLD_READABLE);

    Editor editor = preferences.edit();
    // 存入数据
    editor.putInt("count", ++count);
    // 提交修改
    editor.commit();

    保存

      2:读取数据的程序代码

    try
    {
    // 获取其他程序所对应的Context
    useCount = createPackageContext("org.crazyit.io",  //org.crazyit.io 为上一程序的报名
    Context.CONTEXT_IGNORE_SECURITY);
    }
    catch (NameNotFoundException e)
    {
    e.printStackTrace();
    }
    // 使用其他程序的Context获取对应的SharedPreferences
    SharedPreferences prefs = useCount.getSharedPreferences("count",
    Context.MODE_WORLD_READABLE);
    // 读取数据
    int count = prefs.getInt("count", 0);

    读取
  • 相关阅读:
    力扣题解 125th 验证回文字符串
    力扣题解 242th 有效的字母异位词
    力扣题解 387th 字符串中的第一个唯一字符
    Ubuntu
    Ubuntu
    Ubuntu
    ubuntu
    go-vscode-ubuntu20.04安装部署
    go-vscode-windows安装部署
    2020年任务
  • 原文地址:https://www.cnblogs.com/songyao/p/4081279.html
Copyright © 2020-2023  润新知