不使用GSON保存到SharedPreferences的自定义对象的ArrayList

时间:2018-04-06 06:40:54

标签: android arraylist sharedpreferences pojo gson

我有一个ArrayList个自定义POJO个对象要保存到SharedPreferences,这样它们就不会收集垃圾,用户仍然可以在应用程序关闭后访问它们

我已尝试使用GSON,但我认为我遗漏了一些我看不到的内容。String我的Object转换为已正确保存但没有任何内容存储在其中。

我正在使用此Click event存储:

cartBut.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(getBaseContext(), "Clicked", Toast.LENGTH_SHORT).show();
            SharedPreferences mPrefs = getSharedPreferences("Cart", MODE_PRIVATE);
            SharedPreferences.Editor prefsEditor = mPrefs.edit();

            ArrayList<ItmModel> arrayList = new ArrayList<>();
            AtomicReference<ItmModel> itmModel = new AtomicReference<>(new ItmModel(item.getText().toString(), attr.getText().toString(),
                    pric.getText().toString(), sise.getText().toString(), image, company));
            arrayList.add(itmModel.get());

            Gson gson = new Gson();
            Type type = new TypeToken<ArrayList<ItmModel>>() {
            }.getType();
            String list = gson.toJson(arrayList, type);
            prefsEditor.putString("Cart", list);
            prefsEditor.apply();

        }
    });

我正在检索它:

SharedPreferences sharedPreferences = getSharedPreferences("Cart", MODE_PRIVATE);
    Gson gson = new Gson();
    String list = sharedPreferences.getString("Cart", "");
    Type type = new TypeToken<ArrayList<ItmModel>>() {
    }.getType();
    arrayList = gson.fromJson(list, type);
    if (arrayList == null) {
        arrayList = new ArrayList<>();
    }

    final CrtAdapter crtAdapter = new CrtAdapter(arrayList);

    RecyclerView recyclerView = view.findViewById(R.id.recyclerView);
    recyclerView.setAdapter(crtAdapter);
    recyclerView.setHasFixedSize(true);
    recyclerView.setItemViewCacheSize(20);
    recyclerView.setDrawingCacheEnabled(true);
    recyclerView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
    recyclerView.setLayoutManager(linearLayoutManager);
    runLayoutAnimation(recyclerView);
    recyclerView.setOnFlingListener(null);

尽管我尝试了所有操作,但RecyclerView始终为空,当我在File explorer办理登机手续时,Preference为空screenshot Pic 1 < / p>

和这个

Pic 2

我的POJO同时为ParcelableSerializable。我能做错什么?我会发布任何所需的代码。谢谢。

这就是我从点击事件中的日志中获得的内容。我看到该对象已添加但后来从列表中删除。为什么会发生这种情况?

04-06 09:53:42.959 4078-4078/kamble.gml.woodleyint D/dalvikvm: create interp thread : stack size=128KB
04-06 09:53:42.959 4078-4078/kamble.gml.woodleyint D/dalvikvm: create new thread
04-06 09:53:42.959 4078-4078/kamble.gml.woodleyint D/dalvikvm: new thread created
04-06 09:53:42.959 4078-4078/kamble.gml.woodleyint D/dalvikvm: update thread list
04-06 09:53:42.959 4078-4455/kamble.gml.woodleyint D/dalvikvm: threadid=26: interp stack at 0x57bee000
04-06 09:53:42.959 4078-4455/kamble.gml.woodleyint D/dalvikvm: threadid=26: created from interp
**04-06 09:53:42.960 4078-4078/kamble.gml.woodleyint D/dalvikvm: threadid=26: adding to list**
04-06 09:53:42.960 4078-4078/kamble.gml.woodleyint D/dalvikvm: start new thread
04-06 09:53:42.960 4078-4455/kamble.gml.woodleyint D/dalvikvm: threadid=26: notify debugger
04-06 09:53:42.960 4078-4455/kamble.gml.woodleyint D/dalvikvm: threadid=26 (SharedPreferencesImpl-load): calling run()
04-06 09:53:42.968 4078-4455/kamble.gml.woodleyint D/dalvikvm: threadid=26: exiting
04-06 09:53:42.968 4078-4455/kamble.gml.woodleyint D/dalvikvm: threadid=26: detach (group=0x418d8ce0)
**04-06 09:53:42.968 4078-4455/kamble.gml.woodleyint D/dalvikvm: threadid=26: removing from list
04-06 09:53:42.968 4078-4455/kamble.gml.woodleyint D/dalvikvm: threadid=26: bye!
04-06 09:53:43.143 4078-4078/kamble.gml.woodleyint D/Cart: [[]]**
04-06 09:53:43.146 4078-4078/kamble.gml.woodleyint D/dalvikvm: create interp thread : stack size=128KB
04-06 09:53:43.146 4078-4078/kamble.gml.woodleyint D/dalvikvm: create new thread
04-06 09:53:43.146 4078-4078/kamble.gml.woodleyint D/dalvikvm: new thread created
04-06 09:53:43.146 4078-4078/kamble.gml.woodleyint D/dalvikvm: update thread list
04-06 09:53:43.146 4078-4456/kamble.gml.woodleyint D/dalvikvm: threadid=26: interp stack at 0x57bee000
04-06 09:53:43.146 4078-4456/kamble.gml.woodleyint D/dalvikvm: threadid=26: created from interp
**04-06 09:53:43.146 4078-4078/kamble.gml.woodleyint D/dalvikvm: threadid=26: adding to list**
04-06 09:53:43.146 4078-4078/kamble.gml.woodleyint D/dalvikvm: start new thread
04-06 09:53:43.152 4078-4456/kamble.gml.woodleyint D/dalvikvm: threadid=26: notify debugger
04-06 09:53:43.152 4078-4456/kamble.gml.woodleyint D/dalvikvm: threadid=26 (pool-3-thread-1): calling run()

这是我的POJO

public class ItmModel extends ArrayList implements Parcelable, Serializable {
@SuppressWarnings("unused")
public static final Parcelable.Creator<ItmModel> CREATOR = new Parcelable.Creator<ItmModel>() {
    @Override
    public ItmModel createFromParcel(Parcel in) {
        return new ItmModel(in);
    }

    @Override
    public ItmModel[] newArray(int size) {
        return new ItmModel[size];
    }
};
private String name;
private String attr;
private String size;
private String pric;
private String imag;
private String comp;

public ItmModel(String name, String attr, String size, String pric, String imag, String comp) {
    this.name = name;
    this.attr = attr;
    this.size = size;
    this.pric = pric;
    this.imag = imag;
    this.comp = comp;
}

public ItmModel() {

}

private ItmModel(Parcel in) {
    name = in.readString();
    attr = in.readString();
    size = in.readString();
    pric = in.readString();
    imag = in.readString();
    comp = in.readString();
}

public String getName() {
    return name;
}

public void setName(String companyName) {
    this.comp = companyName;
}

public String getAttr() {
    return attr;
}

public void setAttr(String attr) {
    this.attr = attr;
}

public String getSize() {
    return size;
}

public void setSize(String size) {
    this.size = size;
}

public String getPric() {
    return pric;
}

public void setPric(String pric) {
    this.pric = pric;
}

public String getImag() {
    return imag;
}

public void setImag(String imag) {
    this.imag = imag;
}

public String getComp() {
    return comp;
}

public void setComp(String comp) {
    this.comp = comp;
}

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(name);
    dest.writeString(attr);
    dest.writeString(size);
    dest.writeString(pric);
    dest.writeString(imag);
    dest.writeString(comp);
}}

3 个答案:

答案 0 :(得分:3)

尝试删除AtomicReference并直接将item添加到list,如

ArrayList<ItmModel> arrayList = new ArrayList<>();
ItmModel itmModel = new ItmModel(item.getText().toString(), attr.getText().toString(),pric.getText().toString(), sise.getText().toString(), image, company);
arrayList.add(itmModel);

Gson gson = new Gson();
Type type = new TypeToken<ArrayList<ItmModel>>() {}.getType();
String list = gson.toJson(arrayList, type);
prefsEditor.putString("Cart", list);
prefsEditor.apply();

为什么你甚至在ArrayList中展开POJO,删除并修改部分POJO

以下
public class ItmModel implements Parcelable, Serializable {
@SuppressWarnings("unused")
public static final Parcelable.Creator<ItmModel> CREATOR = new Parcelable.Creator<ItmModel>() {
    @Override
    public ItmModel createFromParcel(Parcel in) {
        return new ItmModel(in);
    }

    @Override
    public ItmModel[] newArray(int size) {
        return new ItmModel[size];
    }
};
@Expose
private String name;
@Expose
private String attr;
@Expose
private String size;
@Expose
private String pric;
@Expose
private String imag;
@Expose
private String comp;
 //rest of code as it is
}

答案 1 :(得分:1)

检查一下,它可能对你有帮助

resolve: {
    alias: {
      '@fortawesome/fontawesome-pro-solid$': '@fortawesome/fontawesome-pro-solid/shakable.es.js',
      '@fortawesome/fontawesome-pro-regular$': '@fortawesome/fontawesome-pro-regular/shakable.es.js',
      '@fortawesome/fontawesome-pro-light': '@fortawesome/fontawesome-pro-light/shakable.es.js'
    }
  },


<i class="fal fa-check"></i> // Does work
<i class="fal fa-github"></i> // Does not work
<i class="fal fa-twitter"></i> // Does not work

这些是我的检索方法,

 private void savePinnedFeedsToPrefrence(int position) {
    PreferenceManager preferenceManager = new PreferenceManager(this);
    Gson gson = new Gson();
    String pinnedList = preferenceManager.getPinnedFeeds(AppConstants.PINNED_FEEDS);
    List<FootballFeed> pinnedFeedsList;
    if ("".contentEquals(pinnedList)) {
        pinnedFeedsList = new ArrayList<>();
    } else {
        pinnedFeedsList = gson.fromJson(pinnedList,
                new TypeToken<List<FootballFeed>>() {
                }.getType());
    }
    pinnedFeedsList.add(footballFeeds.get(position));
    preferenceManager.savePinnedFeeds(gson.toJson(pinnedFeedsList));
}

答案 2 :(得分:1)

To save custom array list you need to follow bellow step:
step 1: You need to creat cutom bean class.
public class Bean {

    String name,number;

    public Bean(String name,String number){
        this.name=name;
        this.number=number;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }
}

step 2: You need to create function to save array list to SharedPreferences.

public void saveArrayList(ArrayList<Bean> list, String key) {

        SharedPreferences prefs = getSharedPreferences("TestDemo", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        Gson gson = new Gson();
        String json = gson.toJson(list);
        editor.putString(key, json);
        editor.apply();     // This line is IMPORTANT !!!

    }

step 3: You need to create function to get array list from SharedPreferences.

    public ArrayList<Bean> getArrayList(String key)
    {

        SharedPreferences prefs = getSharedPreferences("TestDemo", Context.MODE_PRIVATE);
        Gson gson = new Gson();
        String json = prefs.getString(key, null);
        Type type = new TypeToken<ArrayList<Bean>>() {}.getType();
        return gson.fromJson(json, type);

    }

step 4: How to call save and retrieve array list function.

ArrayList<Bean> listSave=new ArrayList<>();
listSave.add(new Bean("test","1"));
listSave.add(new Bean("test","2"));
saveArrayList(listSave,"key");
Log.e("saveArrayList:","Save ArrayList success");
ArrayList<Bean> listGet=new ArrayList<>();
listGet=getArrayList("key");
Log.e("getArrayList:","Get ArrayList size"+listGet.size());

<强> =&GT;别忘了在app app level build.gradle中添加gson库。

实施&#39; com.google.code.gson:gson:2.8.2&#39;