sharedpreferences如何保存对象

    xiaoxiao2026-02-04  0

    昨天做了一个搜索历史的功能,然后根据搜索的历史可以调回到上一个页面,这里涉及到一个用sharedpreferences保存对象的问题,sharedpreferences是不能够直接保存对象的,我们需要将对象序列化成一个字符串进行存储。

    例如:PlayList这样一个对象

    public static void getJsonStringByEntity(Context context, Object object) { String strJson = ""; Gson gson = new Gson(); strJson = gson.toJson(object); saveSharePlayList(context,strJson); } 取出来的时候,我们取出String后,通过json转换为实体对象就好了

    public static PlayList getfromJson(Context context){ PlayList list = null; String str = readSharePlayList(context); if(str!=null){ Gson gson=new Gson(); list = gson.fromJson(str, new TypeToken<PlayList>(){}.getType()); } return list; }

    相关资源:SharedPreferences保存对象jar包
    最新回复(0)