SharedPreferences介绍

   sharedPreferences是通过xml文件来做数据存储的。
        一般用来存放一些标记性的数据,一些设置信息。

        使用sharedPreferences存储数据

            1.通过Context对象创建一个SharedPreference对象
                //name:sharedpreference文件的名称    mode:文件的操作模式
                SharedPreferences sharedPreferences = context.getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
            2.通过sharedPreferences对象获取一个Editor对象
                Editor editor = sharedPreferences.edit();
            3.往Editor中添加数据
                editor.putString("username", username);
                editor.putString("password", password);
            4.提交Editor对象
                editor.commit();

         使用sharedPreferences读取数据

            1.通过Context对象创建一个SharedPreference对象
                SharedPreferences sharedPreferences = context.getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
                
            2.通过sharedPreference获取存放的数据
                //key:存放数据时的key   defValue: 默认值,根据业务需求来写
                String username = sharedPreferences.getString("username", "");
                String password = sharedPreferences.getString("password", "");
                


        通过PreferenceManager可以获取一个默认的sharepreferences对象        
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);

原文地址:https://www.cnblogs.com/xufengyuan/p/5664880.html