我在领域有一个数据库,需要将一个领域对象作为我创建的java对象传递,以便我的适配器识别它。
public final static Parcelable.Creator<MoviePOJO> CREATOR = new Creator<MoviePOJO>() {
@SuppressWarnings({
"unchecked"
})
public MoviePOJO createFromParcel(Parcel in) {
MoviePOJO instance = new MoviePOJO();
instance.posterPath = ((String) in.readValue((String.class.getClassLoader())));
instance.overview = ((String) in.readValue((String.class.getClassLoader())));
instance.releaseDate = ((String) in.readValue((String.class.getClassLoader())));
instance.id = ((Integer) in.readValue((Integer.class.getClassLoader())));
instance.originalTitle = ((String) in.readValue((String.class.getClassLoader())));
instance.backdropPath = ((String) in.readValue((String.class.getClassLoader())));
instance.voteAverage = ((Double) in.readValue((Double.class.getClassLoader())));
return instance;
}
public MoviePOJO[] newArray(int size) {
return (new MoviePOJO[size]);
}
};
是电影创作者,我的RealmObject是:
public class FavoritesItem extends RealmObject implements Parcelable {
@PrimaryKey private Integer movieId;
private String moviePoster;
private String movieBackdrop;
private String movieTitle;
private String movieOverview;
private Double movieRating;
private String movieReleaseDate;
}
如何将其中一个送到另一个?
答案 0 :(得分:0)
假设,正如@ cricket_007建议的那样,你想从Realm DB中获取一个对象,然后将它发送到Intent
上的某个地方(反之亦然),你有两个选择。
到目前为止,最好的办法是避免发送整个对象。如果您只是在自己的应用中发送给Activity
或IntentService
,只需发送主键(可能是movieId
)。收件人可以打开Realm实例并选择相同的对象。 远比甚至分割更快
如果绝对必须包裹,那么您将需要一个适配器,如下所示:
public class MovieParcelable implements Parcelable {
public static final Creator<MovieParcelable> CREATOR = new Creator<MovieParcelable>() {
@Override
public MovieParcelable createFromParcel(Parcel in) {
int id = in.readInt();
String poster = in.readString();
// ...
double rating = in.readDouble();
String releaseDate = in.readString();
return new MovieParcelable(id, poster, ..., rating, releaseDate);
}
@Override
public MovieParcelable[] newArray(int size) {
return new MovieParcelable[size];
}
};
private final Movie movie;
public MovieParcelable(Movie movie) {
this.movie = movie;
}
MovieParcelable(int id, String poster, ..., double rating, String releaseDate) {
this(new Movie(id, poster, ..., rating, releaseDate));
}
public Movie getMovie() { return movie; }
@Override
public int describeContents() { return 0; }
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(movie.getId());
dest.writeString(movie.getPoster());
// ...
dest.writeDouble(movie.getRating());
dest.writeString(movie.getReleaseDate());
}
}