在你投票之前 - 我已经检查过其他帖子和教程,但我需要确定我是否还未阅读,因为这是我第一次尝试使用该库。
在我的应用程序中,我创建了一个ArrayList,它使用不同的字段(主要是字符串和整数)来保存我的日历事件对象(WeekViewEvents):
ArrayList<WeekViewEvent> mNewEvents = new ArrayList<>;
...
WeekViewEvent event = new WeekViewEvent();
event.setName("abc");
event.setId(123);
mNewEvents.add(event);
日历库直接使用该数组(格式) 现在,我想使用Room Persistence Library保存并读取内部存储器中的列表。问题是我不确定:
1)如果我能够加载我的ArrayList并使用它,就像我现在一样,即使它需要@TypeConverter?
2)我可以写下我的@Entity类,如下所示:?
@Entity
public class Events {
@NonNull
@PrimaryKey
public ArrayList<WeekViewEvent> mNewEventsRPL;
public ArrayList<WeekViewEvent> getEvents() {
return mNewEventsRPL;
}
public void setEvents(ArrayList<WeekViewEvent> evenciki) {
this.mNewEventsRPL=evenciki;
}}
3)我使用GSON将单个事件对象转换为String,它看起来像这样:
{"mAllDay":false,"mColor":-6454059,"mEndTime":{"year":2018,"month":0,"dayOfMonth":30,"hourOfDay":16,"minute":46,"second":35},"mId":"111222333","mLocation":"klient","mName":"usluga","mStartTime":{"year":2018,"month":0,"dayOfMonth":30,"hourOfDay":15,"minute":46,"second":35}}
所以现在问题是:我应该如何编写@TypeConverter以便它可以保存和加载我的ArrayList?
先感谢所有愿意做出贡献的人! :)
答案 0 :(得分:0)
以下帮助您找到用于对象列表的转换器。
只需添加“ Object”类,即可代替“ YourClassName ”。
@TypeConverter
public String fromValuesToList(ArrayList<**YourClassName**> parentalRating) {
if (parentalRating == null) {
return (null);
}
Gson gson = new Gson();
Type type = new TypeToken<ArrayList<**YourClassName**>>() {}.getType();
return gson.toJson(parentalRating, type);
}
@TypeConverter
public ArrayList<**YourClassName**> toOptionValuesList(String parentalRatingString) {
if (parentalRatingString == null) {
return (null);
}
Gson gson = new Gson();
Type type = new TypeToken<List<**YourClassName**>>() {
}.getType();
return gson.fromJson(parentalRatingString, type);
}