Android将对象存储到SharedPreferences中

如果需要将一个对象存储到Android SharedPreferences中,可以用到下面的办法:

以我的例子来说,我需要将一个标记账本的对象,其中元素为封面背景id(int)和账本名称(String)的对象存储至SharedPreferences。

下面是我封装改账本(Book)的Bean:

package beans;

/**
 * Created by Chase on 2017/5/3.
 */

public class BookBean {
    public String bookName;
    public int bookBgSrc;

    public BookBean(){

    }


    public BookBean(String bookName,int bookBgSrc){
        this.bookName = bookName;
        this.bookBgSrc =bookBgSrc;
    }

    public String getBookName(){
        return bookName;
    }

    public int getBookBgSrc(){
        return bookBgSrc;
    }

    public void setBookBgSrc(int bookBgSrc) {
        this.bookBgSrc = bookBgSrc;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }
}

下面编写两个方法用来存储和读取这个Bean:

public class SpUtils {
    private static SharedPreferences sp;
   /**
     * 4.存储账本bookBean的list
     */
    public static void putBookBean(Context ctx, List bookList) {
        if (sp == null) {
            sp = ctx.getSharedPreferences("config", MODE_PRIVATE);
        }
        SharedPreferences.Editor editor = sp.edit();
        Gson gson = new Gson();
        String json = gson.toJson(bookList);
        editor.putString(ConstantValue.BOOK_BEAN, json);
        editor.commit();
    }
   }
   /**
     * 读取账本bookBean的list
     */
    public static List getBookBean(Context ctx) {
        if (sp == null) {
            sp = ctx.getSharedPreferences("config", MODE_PRIVATE);
        }
        Gson gson = new Gson();
        String json = sp.getString(ConstantValue.BOOK_BEAN, null);
        Type type = new TypeToken>() {
        }.getType();
        List arrayList = gson.fromJson(json, type);
        return arrayList;
    }

上面读取的Type应该是java.long.reflect的。

参考一些可能出现的错误:
http://stackoverflow.com/questions/43774750/failed-to-deserialized-json-object

`

你可能感兴趣的:(Android将对象存储到SharedPreferences中)