gpt4 book ai didi

java - Realm 对象类 setter 中的枚举支持和自定义逻辑

转载 作者:太空宇宙 更新时间:2023-11-04 12:29:14 25 4
gpt4 key购买 nike

我正在像这样的 Realm 对象类的 setter 和枚举中实现自定义逻辑。-

public class SellerProducts extends RealmObject{

public Boolean isValid=true;
public String is_valid="";
public String quantity;
public int quantity_;
public String enumvalue;
public void setIs_valid(String is_valid){
if (is_valid.equals("0")) {
this.isValid = false;
}
this.is_valid=is_valid;
}
public String getIs_valid(){
return this.is_valid;
}
public void setQuantity(String quantity){
this.quantity=quantity;
try {
quantity_ = Integer.parseInt(this.quantity);
} catch (NumberFormatException e) {
e.printStackTrace();
}
if (!this.isValid) {
setEnum(ProductType.IN_ACTIVE);
} else if (this.quantity_ <= 0) {
setEnum(ProductType.OUT_OF_STOCK);
} else {
setEnum(ProductType.ACTIVE);
}
}

public String getQuantity(){
return this.quantity;
}
public enum ProductType {
ACTIVE, IN_ACTIVE, OUT_OF_STOCK
};
public void setEnum(ProductType val) {
this.enumvalue=val.toString().toUpperCase();
}
public ProductType getEnum() {
return ProductType.valueOf(enumvalue);
}

}

当我从其他 fragment 类调用 getEnum 时,它返回像这样的 null 异常

*java.lang.NullPointerException: name == null
at java.lang.Enum.valueOf(Enum.java:189)
at com.localwizard.realm_db.SellerProducts$ProductType.valueOf(SellerProducts.java:331)
at com.localwizard.realm_db.SellerProducts.getEnum(SellerProducts.java:348)*

我是 Realm 新手,所以我不知道我错在哪里?

最佳答案

Ashish,我认为您没有设置 ProductType 枚举并尝试获取它,并且您收到了异常。这是我尝试过的代码,它工作正常 -

public class OtherFragment {
public static void main(String[] aa)
{
SellerProducts sp = new SellerProducts();
sp.setQuantity("10"); // setting the quantity
System.out.println(sp.getEnum()); // ACTIVE is set as Enum
System.out.println(sp.getQuantity()); // 10
System.out.println(sp.getEnum() == ProductType.ACTIVE); // true
sp.setEnum(ProductType.IN_ACTIVE); // Now IN_ACTIVE is set
System.out.println(sp.getEnum() == ProductType.ACTIVE); // false
}
}

如果这不是您想要的,那么请添加您的代码,您打算如何设置数量并尝试获取枚举值。

如果它回答了您的问题,请接受答案。

关于java - Realm 对象类 setter 中的枚举支持和自定义逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38032529/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com