I migrated from GreenDao3 to ObjectBox, and my project is't build.
I get errors like this
../app/build/generated/source/kapt/indexDebug/com/aff/index/main/boxdb/AliasDao.java
Error:(53, 29) error: cannot find symbol method getContentId()
This was my Alias class in GD3:
import org.greenrobot.greendao.annotation.*;
import com.aff.index.main.db.DaoSession;
import org.greenrobot.greendao.DaoException;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. Enable "keep" sections if you want to edit.
/**
* Entity mapped to table "ALIAS".
*/
#Entity(active = true)
public class Alias {
#Id
private Long id;
private String name;
private String email;
private Long aliasContentId;
/** Used to resolve relations */
#Generated
private transient DaoSession daoSession;
/** Used for active entity operations. */
#Generated
private transient AliasDao myDao;
#ToOne(joinProperty = "aliasContentId")
private Content content;
#Generated
private transient Long content__resolvedKey;
#Generated
public Alias() {
}
public Alias(Long id) {
this.id = id;
}
#Generated
public Alias(Long id, String name, String email, Long aliasContentId) {
this.id = id;
this.name = name;
this.email = email;
this.aliasContentId = aliasContentId;
}
/** called by internal mechanisms, do not call yourself. */
#Generated
public void __setDaoSession(DaoSession daoSession) {
this.daoSession = daoSession;
myDao = daoSession != null ? daoSession.getAliasDao() : null;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Long getAliasContentId() {
return aliasContentId;
}
public void setAliasContentId(Long aliasContentId) {
this.aliasContentId = aliasContentId;
}
/** To-one relationship, resolved on first access. */
#Generated
public Content getContent() {
Long __key = this.aliasContentId;
if (content__resolvedKey == null || !content__resolvedKey.equals(__key)) {
__throwIfDetached();
ContentDao targetDao = daoSession.getContentDao();
Content contentNew = targetDao.load(__key);
synchronized (this) {
content = contentNew;
content__resolvedKey = __key;
}
}
return content;
}
#Generated
public void setContent(Content content) {
synchronized (this) {
this.content = content;
aliasContentId = content == null ? null : content.getId();
content__resolvedKey = aliasContentId;
}
}
/**
* Convenient call for {#link org.greenrobot.greendao.AbstractDao#delete(Object)}.
* Entity must attached to an entity context.
*/
#Generated
public void delete() {
__throwIfDetached();
myDao.delete(this);
}
/**
* Convenient call for {#link org.greenrobot.greendao.AbstractDao#update(Object)}.
* Entity must attached to an entity context.
*/
#Generated
public void update() {
__throwIfDetached();
myDao.update(this);
}
/**
* Convenient call for {#link org.greenrobot.greendao.AbstractDao#refresh(Object)}.
* Entity must attached to an entity context.
*/
#Generated
public void refresh() {
__throwIfDetached();
myDao.refresh(this);
}
#Generated
private void __throwIfDetached() {
if (myDao == null) {
throw new DaoException("Entity is detached from DAO context");
}
}
}
This is the ObjectBox Alias class:
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. Enable "keep" sections if you want to edit.
/**
* Entity mapped to table "ALIAS".
*/
#Entity()
public class Alias {
#Id
private long id;
private String name;
private String email;
private long aliasContentId;
private ToOne<Content> content;
public Alias() {
}
public Alias(long id) {
this.id = id;
}
public Alias(long id, String name, String email, long aliasContentId, ToOne<Content> content) {
this.id = id;
this.name = name;
this.email = email;
this.aliasContentId = aliasContentId;
this.content = content;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public long getAliasContentId() {
return aliasContentId;
}
public void setAliasContentId(long aliasContentId) {
this.aliasContentId = aliasContentId;
}
public ToOne<Content> getContent() {
return content;
}
public void setContent(ToOne<Content> content) {
this.content = content;
}
}
And this is the DAO was generated by ObjectBox
// THIS CODE IS GENERATED BY objectbox, DO NOT EDIT.
/**
* DAO for table "Alias".
*/
public class AliasDao extends AbstractDao<Alias, Long> {
public static final String TABLENAME = "Alias";
/**
* Properties of the Alias box.
*/
private static io.objectbox.EntityInfo BOX_PROPERTIES = new Alias_();
/**
* Properties of entity Alias.<br/>
* Can be used for QueryBuilder and for referencing column names.
*/
public static class Properties {
public final static Property Id = Alias_.id;
public final static Property Name = Alias_.name;
public final static Property Email = Alias_.email;
public final static Property AliasContentId = Alias_.aliasContentId;
public final static Property ContentId = Alias_.contentId;
}
private Query<Alias> content_AliasesQuery;
public AliasDao(Box<Alias> box, IdentityScopeLong<Alias> identityScope) {
super(box, BOX_PROPERTIES, identityScope);
}
public AliasDao(DaoSession daoSession, Box<Alias> box, IdentityScopeLong<Alias> identityScope) {
super(daoSession, box, BOX_PROPERTIES, identityScope);
}
#Override
public void readEntity(Alias from, Alias to) {
to.setId(from.getId());
to.setName(from.getName());
to.setEmail(from.getEmail());
to.setAliasContentId(from.getAliasContentId());
to.setContentId(from.getContentId());
}
#Override
public Long getKey(Alias entity) {
if(entity != null) {
return entity.getId();
} else {
return null;
}
}
#Override
protected final boolean isEntityUpdateable() {
return true;
}
}
This was the Alias Entity at GD3 Daogenerator
Entity alias = schema.addEntity(ENTITY_ALIAS);
alias.addIdProperty();
alias.addStringProperty(PROPERTY_NAME);
alias.addStringProperty(PROPERTY_EMAIL);
Property aliasContentId = alias.addLongProperty("aliasContentId").getProperty();
alias.addToOne(content, aliasContentId);
ToMany contentToAlias = content.addToMany(alias, aliasContentId);
contentToAlias.setName(ALIASES);
I can't find out why Object Box generates getContentId() into the DAO, or how can I resolve it.
contentId is the default name of the property storing the ID of the to-one relation content. Thus, if you want to use aliasContentId instead, you need to specify the name using #TargetIdProperty:
#TargetIdProperty("aliasContentId")
private ToOne<Content> content;
Related
I have pretty normal recyclerview adapter. I pass the list of array to the adapter and trying set images from link as needed with Glide.
Problem is, when I try to get images link with loggin they seem normal, but when I pass data list to adapter they are not working. And giving memory object instead of String.
I should get this:
http://somelin.com/image.jpg
Instead I get this:
package.name.models.responses.chain.Logo_#c170923
What should I do? My adapter works normally as I am using this adapter in other places in the same way and it works.
My adapter
public class ChainAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context mContext;
private List<Restaurant> modelList;
private OnItemClickListener mItemClickListener;
public ChainAdapter(Context context, ArrayList<Restaurant> modelList) {
this.mContext = context;
this.modelList = modelList;
}
public void updateList(ArrayList<Restaurant> modelList) {
this.modelList = modelList;
notifyDataSetChanged();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_chain_list, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
//Here you can fill your row view
if (holder instanceof ViewHolder) {
final Restaurant model = getItem(position);
ViewHolder genericViewHolder = (ViewHolder) holder;
String link = "http://cdn.link.in/unsafe/" + model.getLogo();
System.out.println("chainAdapter " + link);
Glide.with(mContext).load(link).into(genericViewHolder.rest_logo);
CenteredImageSpan imagespan = new CenteredImageSpan(mContext, R.drawable.verified_account);
Spannable text = new SpannableString(model.getName() + " ");
text.setSpan(imagespan, model.getName().length(), model.getName().length() + 1, 0); //text is an object of TextView
if (model.getVerified()) {
genericViewHolder.rest_name.setText(text);
} else {
genericViewHolder.rest_name.setText(model.getName());
}
Calendar today = Calendar.getInstance();
List<Today> hours = model.getToday();
for (Today hour : hours) {
if (hour.getWeekday() == today.get(Calendar.DAY_OF_WEEK) - 1) {
genericViewHolder.restCloseNowIcon.setImageResource(R.drawable.ic_open_now);
genericViewHolder.restCloseNowText.setText(mContext.getString(R.string.open_now));
genericViewHolder.restCloseNowText.setTextColor(mContext.getResources().getColor(R.color.open_now));
} else {
genericViewHolder.restCloseNowIcon.setImageResource(R.drawable.ic_close_now);
genericViewHolder.restCloseNowText.setText(mContext.getString(R.string.close_now));
genericViewHolder.restCloseNowText.setTextColor(mContext.getResources().getColor(R.color.close_now));
}
}
int totalRatings = model.getTotalRatings();
if (totalRatings != 0)
genericViewHolder.restStars.setText((int) totalRatings + "");
}
}
#Override
public int getItemCount() {
return modelList.size();
}
public void SetOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mItemClickListener = mItemClickListener;
}
private Restaurant getItem(int position) {
return modelList.get(position);
}
public interface OnItemClickListener {
void onItemClick(View view, int position, Restaurant model);
}
public class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.imageView8)
ImageView rest_logo;
#BindView(R.id.textView3)
TextView rest_name;
#BindView(R.id.isVerified)
ImageView isVerified;
#BindView(R.id.rest_close_now_icon)
ImageView restCloseNowIcon;
#BindView(R.id.rest_close_now_text)
TextView restCloseNowText;
#BindView(R.id.rest_stars)
TextView restStars;
public ViewHolder(final View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
itemView.setOnClickListener(view -> mItemClickListener.onItemClick(itemView, getAdapterPosition(), modelList.get(getAdapterPosition())));
}
}
}
Model
public class Restaurant implements Parcelable
{
#SerializedName("username")
#Expose
private String username;
#SerializedName("total_ratings")
#Expose
private Integer totalRatings;
#SerializedName("verified")
#Expose
private Boolean verified;
#SerializedName("name")
#Expose
private String name;
#SerializedName("logo")
#Expose
private Logo_ logo;
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("today")
#Expose
private List<Today> today = null;
#SerializedName("thumbnail")
#Expose
private Thumbnail thumbnail;
public final static Creator<Restaurant> CREATOR = new Creator<Restaurant>() {
#SuppressWarnings({
"unchecked"
})
public Restaurant createFromParcel(Parcel in) {
return new Restaurant(in);
}
public Restaurant[] newArray(int size) {
return (new Restaurant[size]);
}
}
;
protected Restaurant(Parcel in) {
this.username = ((String) in.readValue((String.class.getClassLoader())));
this.totalRatings = ((Integer) in.readValue((Integer.class.getClassLoader())));
this.verified = ((Boolean) in.readValue((Boolean.class.getClassLoader())));
this.name = ((String) in.readValue((String.class.getClassLoader())));
this.logo = ((Logo_) in.readValue((Logo_.class.getClassLoader())));
this.id = ((Integer) in.readValue((Integer.class.getClassLoader())));
in.readList(this.today, (Today.class.getClassLoader()));
this.thumbnail = ((Thumbnail) in.readValue((Thumbnail.class.getClassLoader())));
}
/**
* No args constructor for use in serialization
*
*/
public Restaurant() {
}
/**
*
* #param id
* #param logo
* #param username
* #param thumbnail
* #param verified
* #param name
* #param today
* #param totalRatings
*/
public Restaurant(String username, Integer totalRatings, Boolean verified, String name, Logo_ logo, Integer id, List<Today> today, Thumbnail thumbnail) {
super();
this.username = username;
this.totalRatings = totalRatings;
this.verified = verified;
this.name = name;
this.logo = logo;
this.id = id;
this.today = today;
this.thumbnail = thumbnail;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getTotalRatings() {
return totalRatings;
}
public void setTotalRatings(Integer totalRatings) {
this.totalRatings = totalRatings;
}
public Boolean getVerified() {
return verified;
}
public void setVerified(Boolean verified) {
this.verified = verified;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Logo_ getLogo() {
return logo;
}
public void setLogo(Logo_ logo) {
this.logo = logo;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public List<Today> getToday() {
return today;
}
public void setToday(List<Today> today) {
this.today = today;
}
public Thumbnail getThumbnail() {
return thumbnail;
}
public void setThumbnail(Thumbnail thumbnail) {
this.thumbnail = thumbnail;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(username);
dest.writeValue(totalRatings);
dest.writeValue(verified);
dest.writeValue(name);
dest.writeValue(logo);
dest.writeValue(id);
dest.writeList(today);
dest.writeValue(thumbnail);
}
public int describeContents() {
return 0;
}
}
Model Logo_
public class Logo_ implements Parcelable {
#SerializedName("path")
#Expose
private String path;
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("caption")
#Expose
private String caption;
public final static Creator<Logo_> CREATOR = new Creator<Logo_>() {
#SuppressWarnings({
"unchecked"
})
public Logo_ createFromParcel(Parcel in) {
return new Logo_(in);
}
public Logo_[] newArray(int size) {
return (new Logo_[size]);
}
}
;
protected Logo_(Parcel in) {
this.path = ((String) in.readValue((String.class.getClassLoader())));
this.id = ((Integer) in.readValue((Integer.class.getClassLoader())));
this.caption = ((String) in.readValue((String.class.getClassLoader())));
}
/**
* No args constructor for use in serialization
*
*/
public Logo_() {
}
/**
*
* #param id
* #param path
* #param caption
*/
public Logo_(String path, Integer id, String caption) {
super();
this.path = path;
this.id = id;
this.caption = caption;
}
public String getPath() {
return this.path;
}
public void setPath(String path) {
this.path = path;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCaption() {
return caption;
}
public void setCaption(String caption) {
this.caption = caption;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(path);
dest.writeValue(id);
dest.writeValue(caption);
}
public int describeContents() {
return 0;
}
}
As you've discovered the problem is in this line:
String link = "YOUR_URL" + model.getLogo();
Your method getLogo() does not return a string to be appended here, but rather an object of type Logo_. You have 3 options:
Change the method getLogo in your model to return a String (probably the logo filename).
In the Logo object, create another method to return the name and call it like this:
String link = "YOUR_URL" + model.getLogo().getFilename();
3.Override the toString method in your Logo object to return the filename.
#Override
public String toString(){
return this.filename;
}
Edit: You can use the getPath() in your logo POJO:
String link = "YOUR_URL" + model.getLogo().getPath();
In My application I get data from a web service and display those data in recycler view. After that I'm planing to add those data in to local sqlite database and display those data when user open application without internet connection.
Here's a simple model class I'm using to pars JSON result using GSON
public class Repo implements Parcelable {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("url")
#Expose
private String url;
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(this.id);
dest.writeString(this.name);
dest.writeString(this.url);
}
public Repo() {
}
protected Repo(Parcel in) {
this.id = (Integer) in.readValue(Integer.class.getClassLoader());
this.name = in.readString();
this.url = in.readString();
}
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public String getUrl() {
return url;
}
public void setId(Integer id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setUrl(String url) {
this.url = url;
}
public static final Creator<Repo> CREATOR = new Creator<Repo>() {
#Override
public Repo createFromParcel(Parcel source) {
return new Repo(source);
}
#Override
public Repo[] newArray(int size) {
return new Repo[size];
}
};
}
I can create a almost identical model class to represent SQLite data. In here I'm using ORMlite. But this is very similar situation for other ORMs.
#DatabaseTable(tableName = Repo.TABLE_NAME)
public class Repo {
public static final String TABLE_NAME = "repo";
#DatabaseField(columnName = "repo_id")
private long repoId;
#DatabaseField(columnName = "name")
private String name;
public long getRepoId() {
return repoId;
}
public String getName() {
return name;
}
public void setRepoId(long repoId) {
this.repoId = repoId;
}
public void setName(String name) {
this.name = name;
}
}
But by the time I'm trying to save these data in to SQLite database I already have data objects set in GSON model classes. It's kind a redundant thing copy object from GSON model and setting that values in to SQLite model. So I came up with below solution by trying to use single model class to represent both.
#DatabaseTable(tableName = Repo.TABLE_NAME)
public class Repo implements Parcelable {
public static final String TABLE_NAME = "repo";
#DatabaseField(columnName = "repo_id")
#SerializedName("id")
#Expose
private Integer id;
#DatabaseField(columnName = "name")
#SerializedName("name")
#Expose
private String name;
#SerializedName("url")
#Expose
private String url;
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(this.id);
dest.writeString(this.name);
dest.writeString(this.url);
}
public Repo() {
}
protected Repo(Parcel in) {
this.id = (Integer) in.readValue(Integer.class.getClassLoader());
this.name = in.readString();
this.url = in.readString();
}
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public String getUrl() {
return url;
}
public void setId(Integer id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setUrl(String url) {
this.url = url;
}
public static final Creator<Repo> CREATOR = new Creator<Repo>() {
#Override
public Repo createFromParcel(Parcel source) {
return new Repo(source);
}
#Override
public Repo[] newArray(int size) {
return new Repo[size];
}
};
}
I have try this with different type of model class where it only had String type fields. Since GSON uses types like Integer,Boolean That stopping me from using same model for SQLite because database does not identify Integer as a type, in order to work it need to be int.
So what is the professional way to handle this ? Don't I have any other option other than going back to the method of creating two separate model class to represent SQLite and GSON.
Yout approach is absolutely correct, but i think you are putting too much effort reinventing the wheel
You can easily achieve the described task using Room
I've one class, in which array list is there. How to send it through intent. following i did for my class
public class MakeOrder implements Parcelable {
#SerializedName("refno")
#Expose
private String refno;
#SerializedName("ddesc")
#Expose
private String ddesc;
#SerializedName("free")
#Expose
private String free;
#SerializedName("fgift")
#Expose
private String fgift;
#SerializedName("sgift")
#Expose
private String sgift;
#SerializedName("sandage")
#Expose
private SandageResponse sandage;
#SerializedName("inst")
#Expose
private String inst;
#SerializedName("items")
#Expose
private List<Item> items = new ArrayList<Item>();
#SerializedName("discount")
#Expose
private String discount;
#SerializedName("coupon")
#Expose
private Coupon coupon;
#SerializedName("delivery")
#Expose
private String delivery;
#SerializedName("user")
#Expose
private User user;
#SerializedName("otype")
#Expose
private String otype;
#SerializedName("ptype")
#Expose
private String ptype;
#SerializedName("app_id")
#Expose
private String appId;
#SerializedName("app_key")
#Expose
private String appKey;
#SerializedName("request")
#Expose
private String request;
#SerializedName("tablename")
#Expose
private String tablename;
#SerializedName("staff")
#Expose
private String staff;
public String getTablename() {
return tablename;
}
public void setTablename(String tablename) {
this.tablename = tablename;
}
public String getStaff() {
return staff;
}
public void setStaff(String staff) {
this.staff = staff;
}
public String getRefno() {
return refno;
}
public void setRefno(String refno) {
this.refno = refno;
}
public String getDdesc() {
return ddesc;
}
public void setDdesc(String ddesc) {
this.ddesc = ddesc;
}
public String getFree() {
return free;
}
public void setFree(String free) {
this.free = free;
}
public String getFgift() {
return fgift;
}
public void setFgift(String fgift) {
this.fgift = fgift;
}
public String getSgift() {
return sgift;
}
public void setSgift(String sgift) {
this.sgift = sgift;
}
public SandageResponse getSandage() {
return sandage;
}
public void setSandage(SandageResponse sandage) {
this.sandage = sandage;
}
public String getInst() {
return inst;
}
public void setInst(String inst) {
this.inst = inst;
}
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
public String getDiscount() {
return discount;
}
public void setDiscount(String discount) {
this.discount = discount;
}
public Coupon getCoupon() {
return coupon;
}
public void setCoupon(Coupon coupon) {
this.coupon = coupon;
}
public String getDelivery() {
return delivery;
}
public void setDelivery(String delivery) {
this.delivery = delivery;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getOtype() {
return otype;
}
public void setOtype(String otype) {
this.otype = otype;
}
public String getPtype() {
return ptype;
}
public void setPtype(String ptype) {
this.ptype = ptype;
}
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public String getAppKey() {
return appKey;
}
public void setAppKey(String appKey) {
this.appKey = appKey;
}
public String getRequest() {
return request;
}
public void setRequest(String request) {
this.request = request;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.refno);
dest.writeString(this.ddesc);
dest.writeString(this.free);
dest.writeString(this.fgift);
dest.writeString(this.sgift);
dest.writeParcelable(this.sandage, flags);
dest.writeString(this.inst);
dest.writeTypedList(this.items);
dest.writeString(this.discount);
dest.writeParcelable(this.coupon, flags);
dest.writeString(this.delivery);
dest.writeParcelable(this.user, flags);
dest.writeString(this.otype);
dest.writeString(this.ptype);
dest.writeString(this.appId);
dest.writeString(this.appKey);
dest.writeString(this.request);
dest.writeString(this.tablename);
dest.writeString(this.staff);
}
public MakeOrder() {
}
protected MakeOrder(Parcel in) {
this.refno = in.readString();
this.ddesc = in.readString();
this.free = in.readString();
this.fgift = in.readString();
this.sgift = in.readString();
this.sandage = in.readParcelable(SandageResponse.class.getClassLoader());
this.inst = in.readString();
this.items = in.createTypedArrayList(Item.CREATOR);
this.discount = in.readString();
this.coupon = in.readParcelable(Coupon.class.getClassLoader());
this.delivery = in.readString();
this.user = in.readParcelable(User.class.getClassLoader());
this.otype = in.readString();
this.ptype = in.readString();
this.appId = in.readString();
this.appKey = in.readString();
this.request = in.readString();
this.tablename = in.readString();
this.staff = in.readString();
}
public static final Parcelable.Creator<MakeOrder> CREATOR = new Parcelable.Creator<MakeOrder>() {
#Override
public MakeOrder createFromParcel(Parcel source) {
return new MakeOrder(source);
}
#Override
public MakeOrder[] newArray(int size) {
return new MakeOrder[size];
}
};
}
Please take a look of updated one
I'm getting error like unable to marshal value
I made all class Parcelable. how to send its object through Intent
Thanks in Advance
Logcat is like
java.lang.RuntimeException: Parcel: unable to marshal value Models.PlaceOrder.Sub#41e10f80
at android.os.Parcel.writeValue(Parcel.java:1235)
at android.os.Parcel.writeList(Parcel.java:622)
at Models.PlaceOrder.Item.writeToParcel(Item.java:90)
at android.os.Parcel.writeTypedList(Parcel.java:1017)
at Models.PlaceOrder.MakeOrder.writeToParcel(MakeOrder.java:246)
at android.os.Parcel.writeParcelable(Parcel.java:1254)
at android.os.Parcel.writeValue(Parcel.java:1173)
at android.os.Parcel.writeMapInternal(Parcel.java:591)
at android.os.Bundle.writeToParcel(Bundle.java:1627)
at android.os.Parcel.writeBundle(Parcel.java:605)
at android.content.Intent.writeToParcel(Intent.java:6866)
at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:1897)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1418)
at android.app.Activity.internalStartActivityForResult(Activity.java:3427)
at android.app.Activity.access$200(Activity.java:660)
at android.app.Activity$2.onStartActivity(Activity.java:3417)
at android.app.Activity.startActivityForBusiness(Activity.java:5441)
at android.app.Activity.startActivityForResult(Activity.java:3413)
at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:48)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:75)
at android.app.Activity.startActivityForResult(Activity.java:3367)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:871)
at android.app.Activity.startActivity(Activity.java:3644)
at android.app.Activity.startActivity(Activity.java:3612)
Items.java where getting Exception
public class Item implements Parcelable {
#SerializedName("itemid")
#Expose
private String itemid;
#SerializedName("qty")
#Expose
private String qty;
#SerializedName("sub")
#Expose
private List<Sub> sub = new ArrayList<Sub>();
/**
*
* #return
* The itemid
*/
public String getItemid() {
return itemid;
}
/**
*
* #param itemid
* The itemid
*/
public void setItemid(String itemid) {
this.itemid = itemid;
}
/**
*
* #return
* The qty
*/
public String getQty() {
return qty;
}
/**
*
* #param qty
* The qty
*/
public void setQty(String qty) {
this.qty = qty;
}
/**
*
* #return
* The sub
*/
public List<Sub> getSub() {
return sub;
}
/**
*
* #param sub
* The sub
*/
public void setSub(List<Sub> sub) {
this.sub = sub;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.itemid);
dest.writeString(this.qty);
dest.writeList(this.sub);
}
public Item() {
}
protected Item(Parcel in) {
this.itemid = in.readString();
this.qty = in.readString();
this.sub = new ArrayList<Sub>();
in.readList(this.sub, Sub.class.getClassLoader());
}
public static final Parcelable.Creator<Item> CREATOR = new Parcelable.Creator<Item>() {
#Override
public Item createFromParcel(Parcel source) {
return new Item(source);
}
#Override
public Item[] newArray(int size) {
return new Item[size];
}
};
}
You need to implement Parcelable also in the Item and Coupon objects.
Then when you add and read the list in you MakeOrder class:
#Override
public void writeToParcel(Parcel dest, int flags) {
...
// to write the Item list
dest.writeList(items);
// to write Coupon object
dest.writeParcelable(coupon, falgs);
}
BTW, your constructor is empty
private MakeOrder(Parcel in) {
...
// to read the Item list
items = new ArrayList<Item>();
in.readList(items, Item.CREATOR);
// to read Coupon object
in.readParcelable(Coupon.CREATOR);
}
This link could help you:
How to make a class with nested objects Parcelable
And this is the Parcelable documentation:
https://developer.android.com/reference/android/os/Parcel.html
EDIT:
The where more Percel problem added to the question.
Final solution in chat: https://chat.stackoverflow.com/rooms/123710/discussion-between-aman-singh-and-adalpari
You need to put in extras like this:
Intent intent-new Intent(this,YouActvity.class);
intent.putExtra("key",yourModel);
startActivity(intent);
In Activity to retrive:
YouModel yourModel = (YourModel) getIntent().getSerializableExtra("key");
Firstly, your Parcelable constructor is empty. If you leave it empty, then it won't work. You need to read fields from parcel the same order you wrote them in writeToParcel() method.
Then to write parcelable data to intent, putExtra() method of the intent. To extract data from intent, use getParcelableExtra() method of the intent
Try using this
intent.putParcelableArrayListExtra("value", orderList);
And in other Activity get it as:
List<String> orderList=this.getIntent().
getParcelableArrayListExtra("value");
Hope this helps
I'm trying to list objects that have an inner Collection. I can save and retrieve objects just fine, but when I do:
parentRepo.findAll()
Only the last object has it's child object listed, others has an empty collection.
Parent model
#ForeignCollectionField(eager = false)
private Collection<Child> childs;
Child model
#DatabaseField(foreign=true,foreignAutoRefresh=true)
private Parent parent;
eager true or false doesn't make any difference. If i query a child and get its parent, I can get it's children as well. What am I missing?
Edit:
It's working for the modeling that I made. My mistake was that I need a Many-to-many relation between parent and child. I made a quick research and what I need is an intermediate model to achieve this. I'll close this question and will try to made this many-to-many relation between my models.
I solve my Many-to-Many relationships like this:
This is an example from an ongoing project. I have a Many-to-Many relationship between Preparation and GlideWax. To solve it I use thee classes: Preparation, GlideWax and PreparationGlideWax. PreparationGlideWax represents the connections between the the other classes, just like the way you usually solve many-to-many relationships with a table that is a "link" between the tables in the relationship. As you can see GripWax and Structure also has a Many-to_many relationship to preparation. Here is the code:
GlideWax.java
#DatabaseTable(tableName = "glide_waxes")
public class GlideWax {
#DatabaseField(id = true)
private int id;
#DatabaseField(canBeNull = false)
private String name;
#DatabaseField
private String description;
#DatabaseField(canBeNull = false)
private int inUse;
#DatabaseField(foreign=true)
private WaxBrand waxBrand;
#DatabaseField(foreign=true)
private GlideWaxType glideWaxType;
#ForeignCollectionField
private ForeignCollection<PreparationGlideWax> preparationGlideWaxes;
#ForeignCollectionField
private ForeignCollection<TestSessionGlideWax> testSessionGlideWaxes;
public GlideWax() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getInUse() {
return inUse;
}
public void setInUse(int inUse) {
this.inUse = inUse;
}
public WaxBrand getWaxBrand() {
return waxBrand;
}
public void setWaxBrand(WaxBrand waxBrand) {
this.waxBrand = waxBrand;
}
public GlideWaxType getGlideWaxType() {
return glideWaxType;
}
public void setGlideWaxType(GlideWaxType glideWaxType) {
this.glideWaxType = glideWaxType;
}
public ForeignCollection<PreparationGlideWax> getPreparationGlideWaxes() {
return preparationGlideWaxes;
}
public void setPreparationGlideWaxes(ForeignCollection<PreparationGlideWax> preparationGlideWaxes) {
this.preparationGlideWaxes = preparationGlideWaxes;
}
public ForeignCollection<TestSessionGlideWax> getTestSessionGlideWaxes() {
return testSessionGlideWaxes;
}
public void setTestSessionGlideWaxes(ForeignCollection<TestSessionGlideWax> testSessionGlideWaxes) {
this.testSessionGlideWaxes = testSessionGlideWaxes;
}
}
Preparation.java
#DatabaseTable(tableName = "preparations")
public class Preparation {
#DatabaseField(generatedId=true)
private int id;
#ForeignCollectionField
private ForeignCollection<PreparationGlideWax> preparationGlideWaxes;
#ForeignCollectionField
private ForeignCollection<PreparationGripWax> preparationGripWaxes;
#ForeignCollectionField
private ForeignCollection<PreparationStructure> preparationStructures;
#DatabaseField(foreign=true, canBeNull = false)
private SkiPair skiPair;
#DatabaseField(foreign=true, canBeNull = false)
private SkiTester skiTester;
#DatabaseField(foreign=true)
private Rfid rfid;
#DatabaseField(foreign=true, canBeNull = false)
private TestSession testSession;
#ForeignCollectionField
private ForeignCollection<Measurement> measurements;
public Preparation() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public ForeignCollection<PreparationGlideWax> getPreparationGlideWaxes() {
return preparationGlideWaxes;
}
public void setPreparationGlideWaxes(ForeignCollection<PreparationGlideWax> preparationGlideWaxes) {
this.preparationGlideWaxes = preparationGlideWaxes;
}
public ForeignCollection<PreparationGripWax> getPreparationGripWaxes() {
return preparationGripWaxes;
}
public void setPreparationGripWaxes(ForeignCollection<PreparationGripWax> preparationGripWaxes) {
this.preparationGripWaxes = preparationGripWaxes;
}
public ForeignCollection<PreparationStructure> getPreparationStructures() {
return preparationStructures;
}
public void setPreparationStructures(ForeignCollection<PreparationStructure> preparationStructures) {
this.preparationStructures = preparationStructures;
}
public SkiPair getSkiPair() {
return skiPair;
}
public void setSkiPair(SkiPair skiPair) {
this.skiPair = skiPair;
}
public SkiTester getSkiTester() {
return skiTester;
}
public void setSkiTester(SkiTester skiTester) {
this.skiTester = skiTester;
}
public Rfid getRfid() {
return rfid;
}
public void setRfid(Rfid rfid) {
this.rfid = rfid;
}
public TestSession getTestSession() {
return testSession;
}
public void setTestSession(TestSession testSession) {
this.testSession = testSession;
}
}
PreparationGlideWax.java
#DatabaseTable(tableName = "preparation_glide_wax")
public class PreparationGlideWax {
#DatabaseField(generatedId=true)
private int id;
#DatabaseField(canBeNull = false)
private int layer;
#DatabaseField(foreign=true, canBeNull = false)
private GlideWax glideWax;
#DatabaseField(foreign=true, canBeNull = false)
private Preparation preparation;
public PreparationGlideWax() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getLayer() {
return layer;
}
public void setLayer(int layer) {
this.layer = layer;
}
public GlideWax getGlideWax() {
return glideWax;
}
public void setGlideWax(GlideWax glideWax) {
this.glideWax = glideWax;
}
public Preparation getPreparation() {
return preparation;
}
public void setPreparation(Preparation preparation) {
this.preparation = preparation;
}
}
As I said in the edit, I'm able to load the child from parent just fine. My problem is that I need a many-to-many relation between my models. I'll accept this answer in two days.
I am using Sugar ORM 1.3.1 and i am trying to save the following objects
public class Article extends SugarRecord<Article> implements Serializable {
#JsonProperty("Categories")
private List<Category> categories = new ArrayList<Category>();
#JsonProperty("Contents")
private List<Content> contents = new ArrayList<Content>();
#JsonProperty("Country")
private CountryRelated country;
#JsonProperty("Description")
private String description;
#JsonProperty("ExpiryDate")
private String expiryDate;
#JsonProperty("ExtraFields")
private List<ExtraField> extraFields = new ArrayList<ExtraField>();
#JsonProperty("Identifier")
private int identifier;
#JsonProperty("ImageURL")
private String imageURL;
#JsonProperty("Name")
private String name;
#JsonProperty("PortalID")
private int portalID;
#JsonProperty("PublishDate")
private String publishDate;
#JsonProperty("Region")
private Region region;
#JsonProperty("Related")
private List<Related> related = new ArrayList<Related>();
#JsonProperty("Newsbite")
private boolean newsbite;
#JsonProperty("ShareURL")
private String shareURL;
#JsonProperty("Tags")
private List<Tag> tags = new ArrayList<Tag>();
#JsonProperty("Type")
private int type;
public Article() {
}
public Article(List<Category> categories, List<Content> contents, List<ExtraField> extraFields, CountryRelated country, String description, String expiryDate, int identifier, String imageURL, String name, boolean newsbite, int portalID, String publishDate, Region region, List<Related> related, String shareURL, List<Tag> tags, int type) {
this.categories = categories;
this.contents = contents;
this.extraFields = extraFields;
this.country = country;
this.description = description;
this.expiryDate = expiryDate;
this.identifier = identifier;
this.imageURL = imageURL;
this.name = name;
this.newsbite = newsbite;
this.portalID = portalID;
this.publishDate = publishDate;
this.region = region;
this.related = related;
this.shareURL = shareURL;
this.tags = tags;
this.type = type;
}
public List<Category> getCategories() {
return categories;
}
public void setCategories(List<Category> categories) {
this.categories = categories;
}
public List<Content> getContents() {
return contents;
}
public void setContents(List<Content> contents) {
this.contents = contents;
}
public List<ExtraField> getExtraFields() {
return extraFields;
}
public void setExtraFields(List<ExtraField> extraFields) {
this.extraFields = extraFields;
}
public CountryRelated getCountry() {
return country;
}
public void setCountry(CountryRelated country) {
this.country = country;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getExpiryDate() {
return expiryDate;
}
public void setExpiryDate(String expiryDate) {
this.expiryDate = expiryDate;
}
public int getIdentifier() {
return identifier;
}
public void setIdentifier(int identifier) {
this.identifier = identifier;
}
public String getImageURL() {
return imageURL;
}
public void setImageURL(String imageURL) {
this.imageURL = imageURL;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isNewsbite() {
return newsbite;
}
public void setNewsbite(boolean newsbite) {
this.newsbite = newsbite;
}
public int getPortalID() {
return portalID;
}
public void setPortalID(int portalID) {
this.portalID = portalID;
}
public String getPublishDate() {
return publishDate;
}
public void setPublishDate(String publishDate) {
this.publishDate = publishDate;
}
public Region getRegion() {
return region;
}
public void setRegion(Region region) {
this.region = region;
}
public List<Related> getRelated() {
return related;
}
public void setRelated(List<Related> related) {
this.related = related;
}
public String getShareURL() {
return shareURL;
}
public void setShareURL(String shareURL) {
this.shareURL = shareURL;
}
public List<Tag> getTags() {
return tags;
}
public void setTags(List<Tag> tags) {
this.tags = tags;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
}
Category.class
public class Category extends SugarRecord<Category> implements Serializable {
#JsonProperty("Identifier")
private int identifier;
#JsonProperty("Name")
private String name;
public constructor + getters and setters }
Content.class and CountryRelated.class have same structure
after i do article.save() my lists doesnt save . Am i doing something wrong or it doesnt save lists at all ???
I few things to look at.
First. I do not believe that the database will handle a column with the type of List or a type of other Object. When I tried running your code, I received:
Class cannot be read from Sqlite3 database. Please check the type of field categories(java.util.List)
These should be types the database can store. Try serializing your List(s) to Strings to insert them in the db. You can try doing this in your getter and setter. The setter takes the list of objects and converts it to a serialized String, the getter takes the serialized String and converts it back to a list of objects.
In the instance of SugarOrm, you can reference another table and it will create a relationship outlined here:
http://satyan.github.io/sugar/creation.html#why
Notice the "Author" type is just referencing a record from another table in the database.
Second I usually try and set my default values inside my default constructor. so something like:
... property declarations...
public Article() {
this.name = "Default Value";
}
Hope this helps you finish troublshooting!