• Android 使用SharedPreference来进行软件配置的存取


    我们在安卓开发的时候不免需要记录用户键入的一些信息,比如账号和密码,用户使用软件的次数,上次打开软件的时间等等,为了保存这些配置,我们可以使用SharedPreference类保存他们。

            //使用SharedPreference进行保存软件的配置信息
            SharedPreferences sharedPreferences = this.getSharedPreferences("config", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            String username = "wuyou";//这里假设获得用户名
            String password = "password";//假设获得密码
            //将值添加到editor
            editor.putString("username", username);
            editor.putString("password", password);
            //跟数据库一样,需要提交
            editor.commit();

    向editor里面添加完所有的数据之后,要调用editor.commit()提交。

    提交之后会产生一个目录:/data/data/包名/shared_prefs,在这个目录中有一个xml文件,在本例中,文件名为config.xml。这个文件名取决于getSharedPreference方法的第一个参数。

    下面演示保存配置文件之后进行提取信息:

            //使用SharedPreference获取已经保存的配置信息
            SharedPreferences sp = this.getSharedPreferences("config", Context.MODE_PRIVATE);
            //第一个参数为key,第二个参数为默认值(如果找不到该值)
            String username = sp.getString("username", "");
            String password = sp.getString("password", "");
            Log.i("username", username);
            Log.i("password", password);
  • 相关阅读:
    grant授权“失败”的原因
    解决:error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)'
    3.MySQL之创建/删除用户
    Linux常用宏contianer_of()
    Linux设备模型(一)_基本概念
    内核探测工具systemtap简介
    模块驱动调试记录 ——platform_driver_register
    Linux软件栈上的性能诊断工具集
    系统调用—sysconf
    C的编译&预编译
  • 原文地址:https://www.cnblogs.com/wuyou/p/3418180.html
Copyright © 2020-2023  润新知