使用SharedPreference存储对象集合

开发中有时需要存储对象集合,使用数据库又大材小用啦,所以这个时候可以使用SharedPreference,下面就是为了以后使用方便封装的工具类:

public class ListDataSaveUtil {

    private static final String DEFAULT_SP_NAME = "default_sp";
    private static final String key = "record";

    public static<T> List<T> getObject(Context context,Class<T> cls) {
        List<T> datalist=new ArrayList<T>();
        String json = getString(context, key, null);
        if (TextUtils.isEmpty(json)) {
            return null;
        }
        try {
            Gson gson = new Gson();
            JsonArray arry = new JsonParser().parse(json).getAsJsonArray();
            for (JsonElement jsonElement : arry) {
                datalist.add(gson.fromJson(jsonElement, cls));
            }

            return datalist;
        } catch (Exception e) {
            return null;
        }
    }

    public static<RouteType> void putObject(Context context, List<RouteType> datalist) {
        if (null == datalist || datalist.size() <= 0)
            return;
        Gson gson = new Gson();
        String json = gson.toJson(datalist);
        putString(context, key, json);
    }

    private static void putString(Context context, String key, String value) {
        SharedPreferences sp = context.getSharedPreferences(DEFAULT_SP_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.putString(key, value);
        edit.commit();
    }

    public static String getString(Context context, String key, String defValue) {
        SharedPreferences sp = context.getSharedPreferences(DEFAULT_SP_NAME, Context.MODE_PRIVATE);
        return sp.getString(key, defValue);
    }
}

在需要存储的地方调用:

List<RouteType> list = ListDataSaveUtil.getObject(getApplicationContext(),RouteType.class);
    if (list == null){
		list = new ArrayList<>();
    }else {
        Iterator<RouteType> it=list.iterator();
        while(it.hasNext()){
            RouteType routeType = it.next();
            if(data.get(position).startStation.equals(routeType.startStation) && 	 data.get(position).endStation.equals(routeType.endStation)) {
            it.remove();}}
            }
            RouteType routeType = new RouteType();
            routeType.type = "2";
            routeType.startStation = data.get(position).startStation;
            routeType.endStation = data.get(position).endStation;
            routeType.routeName = data.get(position).routeName;
            routeType.title = data.get(position).routeName+"路("+data.get(position).startStation+"-"+data.get(position).endStation+")";
            list.add(routeType);
            ListDataSaveUtil.putObject(getApplicationContext(),list);

在需要取数据的地方调用:

List<RouteType> list = ListDataSaveUtil.getObject(getApplicationContext(),RouteType.class);

猜你喜欢

转载自blog.csdn.net/JustinNick/article/details/81542614