I'm Using Room to do data persistence, What I want to to is to Have two methods
called stringToObject(String data)
to
handle all the Type Converting for multiple classes
like: MoviesList
& ReviewList
&TrailerList
when I run the App I get this error :
error: Cannot use unbound generics in Type Converters.
public class Converters{
public static Gson gson = new Gson();
@TypeConverter
public static <T> List<T> stringToObject(String data) {
if (data == null) {
return Collections.emptyList();
}
Type listType = new TypeToken<List<T>>(){}.getType();
return gson.fromJson(data, listType);
}
@TypeConverter
public static <T> String ObjectToString(List<T> someObjects) {
return gson.toJson(someObjects);
}
}
public class ReviewList {
@SerializedName("id")
private Integer id;
@SerializedName("page")
private Integer page;
@SerializedName("results")
private List<Review> reviewList = null;
@SerializedName("total_pages")
private Integer totalPages;
@SerializedName("total_results")
private Integer totalResults;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getPage() {
return page;
}
public void setPage(Integer page) {
this.page = page;
}
public List<Review> getReviewList() {
return reviewList;
}
public void setReviewList(List<Review> reviewList) {
this.reviewList = reviewList;
}
....
}
public class TrailerList {
@SerializedName("id")
private Integer id;
@SerializedName("results")
private List<Trailer> trailers = null;
public List<Trailer> getTrailers() {
return trailers;
}
public void setTrailers(List<Trailer> trailers) {
this.trailers = trailers;
}
....
What is Cussing The Error ?
How Can I fix it ?
Yes! that's possible! for others who want to use generic type converters
for room, Here is my approach:
public abstract class BaseConverter<T> {
private final Gson gson;
private final Type type;
public BaseConverter(Type type) {
this.type = type;
this.gson = new GsonBuilder()
.serializeNulls()
.setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
.create();
}
@TypeConverter
public List<T> mapStringToList(String value) {
return gson.fromJson(value, type);
}
@TypeConverter
public String mapListToString(List<T> value) {
return gson.toJson(value, type);
}
}
Now you can create your own converters. for example:
public class UserConverter extends BaseConverter<User> {
public UserConverter() {
super(new TypeToken<List<User>>() {}.getType());
}
}
Then add your type converters to room configs:
@TypeConverters({
UserConverter.class
})
public abstract class RoomDB extends RoomDatabase {
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With