好的,所以我为我的Android应用程序实现了Realm。该应用程序基本上是一个会计购物列表混合,用户添加他或她已购买的项目。
在我的Accounting
类中,它包含Realm数据库实现,添加项的方法将一个int返回到我的主Activity,以便在RecyclerAdapter.notifyItemInserted
中使用。
以下是该方法的工作原理
public int addItem(final Item latestItem) {
mRealm.beginTransaction();
Number firstId = mRealm.where(Item.class).max("ID");
int nextId = firstId != null ? firstId.intValue() + 1 : 0;
Item firstItem = mRealm.where(Item.class)
.equalTo("mName", latestItem.getName())
.equalTo("mPrice", latestItem.getPrice())
.findFirst();
if (firstItem == null) {
latestItem.setID(nextId);
mRealm.copyToRealm(latestItem);
} else {
firstItem.setCount(firstItem.getCount() + latestItem.getCount());
}
mRealm.commitTransaction();
updateItemList();
int index = mItemList.indexOf(latestItem);
return index;
问题是索引是-1
,即对象不存在于List对象中,我填充了数据库对象,如下所示:
private void updateItemList() {
mItemList = mRealm.where(Item.class).findAllSorted("mPrice", Sort.DESCENDING);
}
我尝试从数据库中手动检索对象,并将其显示为RealmProxyItem
。对equals()
的测试返回false。施放只是抛出ClassCastException
。
如何确保equals()
返回true?
Item.java
public class Item extends RealmObject{
@PrimaryKey
private int ID;
private String mName;
private double mPrice;
private int mCount;
private int mItemType;
public Item() {/** Required due to Realm **/ }
public Item(String mName, double mPrice, int count, int itemType) {
this.mName = mName;
this.mPrice = mPrice;
this.mCount = count;
this.mItemType = itemType;
this.ID = 0;
}
/**public Item(String mName, double mPrice, int count) {
this(mName, mPrice, count, ItemType.NO_TYPE);
} **/
public String getName() {
return mName;
}
public void setName(String name) {
mName = name;
}
public double getPrice() {
return mPrice;
}
public int getCount() {
return mCount;
}
public void setCount(int count) {
mCount = count;
}
public int getItemType() {
return mItemType;
}
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
/** public ItemType getItemType() {
return mItemType;
} **/
@Override
public boolean equals(Object object) {
if (object == null) return false;
else if (object.getClass() != this.getClass()) return false;
Item item = (Item) object;
if (!item.getName().equals(this.getName())) return false;
else if (item.getPrice() != this.getPrice()) return false;
//else if (!item.getItemType().equals(this.getItemType())) return false;
return true;
}
@Override
public int hashCode() {
int hash = 5;
hash = 17 * hash + this.mName.hashCode();
hash = 17 * hash + (int) (Double.doubleToLongBits(this.mPrice) ^ (Double.doubleToLongBits(this.mPrice) >>> 32));
return hash;
}
public void increaseCountBy(int amount) {
mCount += amount;
}
}
答案 0 :(得分:2)
由于您的模型中有主键我会说您将equals()
方法更改为:
@Override
public boolean equals(Object object) {
if (object == null || !(object instanceof Item)) return false;
Item item = (Item) object;
return item.getID() == ID;
}