常用代码整理:配置文件工具类(SPUtil)

版权声明:本文为博主原创文章,转载请标明出处。 https://blog.csdn.net/zeqiao/article/details/82862079

说明:大部分内容都是参考别的文章,这里做整理是为了以后的编程有实用的模板,可以即需即用。

import android.content.Context;
import android.content.SharedPreferences;

import java.util.ArrayList;
import java.util.List;

public class SPUtil {

    private static final String PREFERENCES_FILE_NAME = "com.xq.shared_preferences";
    private static SharedPreferences mSharedPreferences = MyApplication.getInstance().getSharedPreferences(PREFERENCES_FILE_NAME, Context.MODE_PRIVATE);
    private static SharedPreferences.Editor mEditor = mSharedPreferences.edit();

    /**
     * 保存一个 String 类型的值
     */
    public static boolean putString(String key, String value) {
        return mEditor.putString(key, value).commit();
    }

    /**
     * 获取 String 的 value
     */
    public static String getString(String key, String defValue) {
        return mSharedPreferences.getString(key, defValue);
    }

    /**
     * 保存一个 Boolean 类型的值
     */
    public static boolean putBoolean(String key, Boolean value) {
        return mEditor.putBoolean(key, value).commit();
    }

    /**
     * 获取 boolean 的 value
     */
    public static boolean getBoolean(String key, Boolean defValue) {
        return mSharedPreferences.getBoolean(key, defValue);
    }

    /**
     * 保存一个 int 类型的值
     */
    public static boolean putInt(String key, int value) {
        return mEditor.putInt(key, value).commit();
    }

    /**
     * 获取 int 的 value
     */
    public static int getInt(String key, int defValue) {
        return mSharedPreferences.getInt(key, defValue);
    }

    /**
     * 保存一个 float 类型的值
     */
    public static boolean putFloat(String key, float value) {
        return mEditor.putFloat(key, value).commit();
    }

    /**
     * 获取 float 的 value
     */
    public static float getFloat(String key, Float defValue) {
        return mSharedPreferences.getFloat(key, defValue);
    }

    /**
     * 保存一个 long 类型的值
     */
    public static boolean putLong(String key, long value) {
        return mEditor.putLong(key, value).commit();
    }

    /**
     * 获取 long 的 value
     */
    public static long getLong(String key, long defValue) {
        return mSharedPreferences.getLong(key, defValue);
    }

    /**
     * 存储 List<String>
     */
    public static void putStrListValue(String key, List<String> strList) {
        if (null == strList) {
            return;
        }
        // 保存之前先清理已经存在的数据,保证数据的唯一性
        removeStrList(key);
        int size = strList.size();
        putInt(key + "size", size);
        for (int i = 0; i < size; i++) {
            putString(key + i, strList.get(i));
        }
    }

    /**
     * 获取 List<String>
     */
    public static List<String> getStrListValue(String key) {
        List<String> strList = new ArrayList<String>();
        int size = getInt(key + "size", 0);
        for (int i = 0; i < size; i++) {
            strList.add(getString(key + i, null));
        }
        return strList;
    }

    /**
     * 清空 List<String>
     */
    public static void removeStrList(String key) {
        int size = getInt(key + "size", 0);
        if (0 == size) {
            return;
        }
        remove(key + "size");
        for (int i = 0; i < size; i++) {
            remove(key + i);
        }
    }

    /**
     * 清空对应 key 数据
     */
    public static boolean remove(String key) {
        return mEditor.remove(key).commit();
    }

}
public class MyApplication extends Application {

    private static MyApplication mMyApplication;

    public static MyApplication getInstance() {
        return mMyApplication;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mMyApplication = this;
    }
}

一、概述

1、SharedPreferences 是 Android中 常用的数据存储方式,SharedPreferences 采用 key-value(键值对)形式,主要用于轻量级的数据存储,尤其适合保存应用的配置参数,但不建议使用 SharedPreferences 来存储大规模的数据,可能会降低性能。如果一个 SharedPreferences 对应的 xml 文件很大的话,在初始化时会把这个文件的所有数据都加载到内存中,这样就会占用大量的内存,有时我们只是想读取某个 xml 文件中一个 key 的 value,结果它把整个文件都加载进来了,如果必要的话需要进行相关优化处理(比如在子线程中加载)。
2、SharedPreferences 采用 xml 文件格式来保存数据,文件所在目录位于 /data/data/<package_name>/shares_prefs。
3、PreferencesMode:

  • Context.MODE_PRIVETE:指定该 SharedPreferences 数据只能被本应用程序读写。
  • Context.MODE_APPEND:检查文件是否存在,存在就往文件追加内容,否则就创建新文件。
  • Context.MODE_WORLD_READABLE:指定该 SharedPreferences 数据能被其他应用程序读,但不能写。
  • Context.MODE_WORLD_WRITEABLE:指定该 SharedPreferences 数据能被其他应用程序读写。

二、注意事项

1、getSharedPreferences() 是从 ContextImpl.sSharedPrefsCache 获取唯一的 SPI 对象。对于一个相同的SharedPreferences name,获取到的都是同一个 SharedPreferences 对象,它其实是一个 SharedPreferencesImpl 对象。
2、每次 edit 都会创建一个新的 EditorImpl 对象。最好不要连续多次 edit(),应该获取一次 edit(),然后多次执行 putXxx(),最后统一提交,减少内存波动。

有这样一种情况,有时 SharePreferences.Editor 未用临时变量存储,会出现存储不了数据的情况:
sp.edit().putString(“key”, “value”) // 这样写有时会出现存储不了的情况
SharedPreferences.Editor editor = sp.edit(); // 临时变量

三、SharedPreference.Editor 的 apply() 和 commit()

1、apply() 没有返回值,而 commit() 返回 boolean 表明修改是否提交成功。
2、apply() 是将修改数据原子提交到内存,而后异步真正提交到硬件磁盘;而 commit() 是同步的提交到硬件磁盘,因此,在多个并发的提交 commit() 的时候,他们会等待正在处理的 commit() 保存到磁盘后在操作,从而降低了效率。而 apply() 只是原子的提交到内容,后面有调用 apply() 的函数的将会直接覆盖前面的内存数据,这样从一定程度上提高了很多效率。commit() 的写操作是在调用线程中执行的,而 apply() 内部是用一个单线程的线程池实现的,因此写操作是在子线程中执行的。
3、apply() 方法失败时,不会有任何失败的提示。
综合上述,由于在一个进程中,sharedPreference 是单实例,一般不会出现并发冲突,如果对提交的结果不关心的话,建议使用 apply(),当然需要确保提交成功且有后续操作的话,还是需要用 commit() 的。


参考文章:
1、http://tanqi0508.blog.163.com/blog/static/1883557772012111104326404/
2、https://blog.csdn.net/u012619640/article/details/50940074
3、https://www.cnblogs.com/zhangmiao14/p/7209302.html
4、https://blog.csdn.net/chark_leo/article/details/45564369
5、https://blog.csdn.net/hty1053240123/article/details/79202611

猜你喜欢

转载自blog.csdn.net/zeqiao/article/details/82862079
今日推荐