I'm implementing custom logic in setters and enums in realm object class like this.-
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);
}
}
when i am calling getEnum from the other fragment class it is returning null exception like this
*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)*
I'm new to realm so I don't know where I'm wrong?
Ashish, i think you are not setting the ProductType enum and trying to get it and you geeting the exception. Here is the code which i have tried and it is working fine -
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
}
}
If this is not what you want then please add your peace of code, how you meant to set the quantity and trying to get the enum value.
If it answers your question then please accept the answer.
Related
I need to make a programm which is like a rally, theres 2 types of vehicles, motorcycle and cars, two types of motorcycle, with and without sidecar, the thing is that I need to verify if there is just a motorcycle in an array list, I mean, two wheels vehicle. That verification should be done in a method called esDe2Ruedas(), which is called by an abstract overrided method called check() that should be the one that verifies if a group of vehicles from an array are able to run in the rally, if its true all the elements of the array must be from the same type.
Here is the code
this is how the program arrays the vehicles
GrandPrix gp1 = new GrandPrix();
gp1.agregar(v1);
//gp1.mostrar(v1);
gp1.agregar(v2);
System.out.println(gp1.check());
GrandPrix gp2 = new GrandPrix();
gp2.agregar(vt1);
gp2.agregar(vt2);
gp2.agregar(m2);
System.out.println(gp2.check());
GrandPrix gp3 = new GrandPrix();
gp3.agregar(vt1);
gp3.agregar(vt2);
gp3.agregar(m1);
System.out.println(gp3.check());
GrandPrix gp4 = new GrandPrix();
gp4.agregar(m1);
gp4.agregar(m2);
System.out.println(gp4.check());
This is the class that is using
import java.util.ArrayList;
public class GrandPrix extends Rally{
ArrayList<Vehiculo> ve = new ArrayList<Vehiculo>();
public void agregar(Vehiculo v) {
ve.add(v);
}
public void agregar(Carro c) {
ve.add(c);
}
public void agregar(Moto m) {
ve.add(m);
}
#Override
boolean check() {// HERE I VERIFY IF THE VEHICLES ARE COMPATIBLE
return false;
}
}
This is the class where everything goes on
public class Vehiculo {
private String Nombre;
private double velocidad_max;
private int peso;
private int comb;
public Vehiculo() {
setNombre("Anónimo");
setVel(130);
setPeso(1000);
setComb(0);
}
public Vehiculo(String string, double d, int i, int j) {
setNombre(string);
setVel(d);
setPeso(i);
setComb(j);
}
double rendimiento() {
return velocidad_max/peso;
}
public boolean mejor(Vehiculo otroVehiculo) {
return rendimiento()>otroVehiculo.rendimiento();
}
public String toString() {
return getNombre()+"-> Velocidad máxima = "+getVel()+" km/h, Peso = "+getPeso()+" kg";
}
/**************************************
---------SET And GET Nombre------------
***************************************/
public String getNombre() {
return Nombre;
}
public void setNombre(String nuevoNombre) {
this.Nombre=nuevoNombre;
}
/**************************************
---------SET And GET velocidad_max------------
***************************************/
public double getVel() {
return velocidad_max;
}
public void setVel(double nuevaVel) {
this.velocidad_max=nuevaVel;
}
/**************************************
---------SET And GET peso------------
***************************************/
public double getPeso() {
return peso;
}
public void setPeso(int nuevoPeso) {
this.peso=nuevoPeso;
}
/**************************************
---------SET And GET comb------------
***************************************/
public int getComb() {
return comb;
}
public void setComb(int comb) {
this.comb = comb;
}
boolean esDe2Ruedas() {
return false;
}
}
This is the class of motorcycles, which is in theory the same as the car's class, without sidecar thing
public class Moto extends Vehiculo{
private boolean sidecar;
public Moto(String string, double d, int i, int j) {
setNombre(string);
setVel(d);
setPeso(i);
setComb(j);
setSidecar(false);
}
public Moto(String string, double d, int i, int j, boolean b) {
setNombre(string);
setVel(d);
setPeso(i);
setComb(j);
setSidecar(b);
esDe2Ruedas(false);
}
public String toString() {
String str = null;
if(isSidecar())
str =super.toString()+", Moto, con sidecar";
else
str =super.toString()+", Moto";
return str;
}
public boolean isSidecar() {
return sidecar;
}
public void setSidecar(boolean sidecar) {
this.sidecar = sidecar;
}
I guess what you presented is what is given. If you came up with the design it is ok, but I believe it could be improved. Anyway, I try to respond to what I believe was your question straight away.
Vehiculo is the super type of Moto (which can have a side car and becomes 3 wheeler).
Vehiculo has a method esDe2Ruedas, which returns false.
Moto inherits that method <-- this is wrong, it should override it and, depending on side car, return the expected boolean value.
In the check method you can now distinguish between Moto and "Moto with sidecar" by using that method.
We're updating a Hibernate (3.6) application that defines a custom type for money, extending org.hibernate.type.ImmutableType. It's been fairly straightforward to make it instead extend AbstractSingleColumnStandardBasicType and create a Java type descriptor to store Money as BigInteger.
However, various parts of the application use HQL queries that perform aggregate functions (usually SUM) on money fields. The old style, extending ImmutableType, automatically converted the result to Money, but with the new style, that's not happening; the result is a Long.
Does anyone know how to make Hibernate custom types automatically convert the result of aggregate functions?
Old user type:
public class MoneyUserType extends ImmutableType {
private final BigIntegerType bigIntegerType = new BigIntegerType();
#Override
public Object fromStringValue(final String string) {
final BigInteger bigInteger = (BigInteger) bigIntegerType.fromStringValue(string);
return Money.inCents(bigInteger);
}
#Override
public Object get(final ResultSet rs, final String name) throws SQLException {
final BigInteger bigInteger = (BigInteger) bigIntegerType.get(rs, name);
if (null == bigInteger) {
return null;
}
return Money.inCents(bigInteger);
}
#Override
public void set(final PreparedStatement st, final Object object, final int index) throws SQLException {
final Money money = (Money) object;
bigIntegerType.set(st, money.getAmountInCents(), index);
}
#Override
public int sqlType() {
return bigIntegerType.sqlType();
}
#Override
public String toString(final Object object) {
final Money money = (Money) object;
return bigIntegerType.toString(money.getAmountInCents());
}
public String getName() {
return Money.class.getName();
}
#SuppressWarnings("unchecked")
public Class getReturnedClass() {
return Money.class;
}
}
New user type:
public class MoneyUserType extends AbstractSingleColumnStandardBasicType<Money> {
public MoneyUserType() {
super(BigIntTypeDescriptor.INSTANCE, MoneyJavaTypeDescriptor.INSTANCE);
}
#Override
public String getName() {
return Money.class.getName();
}
}
public class MoneyJavaTypeDescriptor extends AbstractTypeDescriptor<Money> {
public static final MoneyJavaTypeDescriptor INSTANCE = new MoneyJavaTypeDescriptor();
public MoneyJavaTypeDescriptor() {
super(Money.class, ImmutableMutabilityPlan.INSTANCE);
}
#Override
public Money fromString(final String string) {
final BigInteger bigInteger = BigIntegerTypeDescriptor.INSTANCE.fromString(string);
return Money.inCents(bigInteger);
}
#Override
public <X> X unwrap(Money value, Class<X> type, WrapperOptions options) {
if (value == null) {
return null;
}
if (type.isAssignableFrom(BigInteger.class)) {
return (X) value.getAmountInCents();
}
if (type.isAssignableFrom(Long.class)) {
return (X) Long.valueOf(value.getAmountInCents().longValue());
}
if (type.isAssignableFrom(Integer.class)) {
return (X) Integer.valueOf(value.getAmountInCents().intValue());
}
throw unknownUnwrap(type);
}
#Override
public <X> Money wrap(X value, WrapperOptions options) {
if (value == null) {
return null;
}
if (Number.class.isInstance(value)) {
return Money.inCents((Number) value);
}
throw unknownWrap(value.getClass());
}
#Override
public String toString(final Money money) {
return BigIntegerTypeDescriptor.INSTANCE.toString(money.getAmountInCents());
}
}
Looks like we can work around this by adding extra setters on our DTOs and putting aliases in the queries as per Custom type / converter in conjunction with Hibernate's Transformers.aliasToBean
It's not ideal but it can be made to work.
You can add an INSTANCE static field to your MoneyUserType:
public class MoneyUserType extends AbstractSingleColumnStandardBasicType<Money> {
public static final MoneyUserType INSTANCE = new MoneyUserType();
// ...
}
then add for example the following function to your custom hibernate dialect:
public class MyPostgreSQLDialect extends PostgreSQL10Dialect
{
public MyPostgreSQLDialect()
{
registerFunction("sum_money", new StandardSQLFunction("sum", MoneyUserType.INSTANCE));
}
}
declare this dialect in your persistence.xml or hibernate.cfg.xml
and then you will be able to use the sum_money function in your hql:
Money sum = entityManager.createQuery(
"select sum_money(m.money) from MoneyEntity m",
Money.class
).getSingleResult();
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I do not understand when my program reads my yml file, it read the type of float but it returns zero or 0.0. I have my float TRIG_EDGE_LEV which return 0.0 but it sould returns 1.5.
public class Loadyml {
//static OscilloDSO1072B dso1072B = new OscilloDSO1072B("visa://192.168.53.67/USB0::0x0957::0x0588::CN55040484::INSTR") ;
private String TRIG_EDGE_SLOP;
private String ENABLE_CHAN_OFFSET;
private float TRIG_EDGE_LEV;
private String TIM_MODE;
private String SCALE_NUMBER;
private String TIM_MAIN_SCAL;
private String SCALE_CHAN;
private String TRIG_EDGE_SOURCE;
private String WAV_SOUR;
private String PROB_CHAN;
private String INVERSE_CHAN;
private String WAV_POINT_MODE;
private String DISPLAY_CHAN;
private String ENABLE_CHAN_BWL_OFF;
private String COUPLING_CHAN;
private String OFFSET_NUMBER;
private String WAV_FORM;
public String getTRIG_EDGE_SLOP() {
return TRIG_EDGE_SLOP;
}
public void setTRIG_EDGE_SLOP(String TRIG_EDGE_SLOP) {
this.TRIG_EDGE_SLOP = TRIG_EDGE_SLOP;
}
public String getENABLE_CHAN_OFFSET() {
return ENABLE_CHAN_OFFSET;
}
public void setENABLE_CHAN_OFFSET(String ENABLE_CHAN_OFFSET) {
this.ENABLE_CHAN_OFFSET = ENABLE_CHAN_OFFSET;
}
public float getTRIG_EDGE_LEV() {
return TRIG_EDGE_LEV;
}
public void setTRIG_EDGE_LEV(float TRIG_EDGE_LEV) {
this.TRIG_EDGE_LEV = TRIG_EDGE_LEV;
}
public String getTIM_MODE() {
return TIM_MODE;
}
public void setTIM_MODE(String TIM_MODE) {
this.TIM_MODE = TIM_MODE;
}
public String getSCALE_NUMBER() {
return SCALE_NUMBER;
}
public void setSCALE_NUMBER(String SCALE_NUMBER) {
this.SCALE_NUMBER = SCALE_NUMBER;
}
public String getTIM_MAIN_SCAL() {
return TIM_MAIN_SCAL;
}
public void setTIM_MAIN_SCAL(String TIM_MAIN_SCAL) {
this.TIM_MAIN_SCAL = TIM_MAIN_SCAL;
}
public String getSCALE_CHAN() {
return SCALE_CHAN;
}
public void setSCALE_CHAN(String SCALE_CHAN) {
this.SCALE_CHAN = SCALE_CHAN;
}
public String getTRIG_EDGE_SOURCE() {
return TRIG_EDGE_SOURCE;
}
public void setTRIG_EDGE_SOURCE(String TRIG_EDGE_SOURCE) {
this.TRIG_EDGE_SOURCE = TRIG_EDGE_SOURCE;
}
public String getWAV_SOUR() {
return WAV_SOUR;
}
public void setWAV_SOUR(String WAV_SOUR) {
this.WAV_SOUR = WAV_SOUR;
}
public String getPROB_CHAN() {
return PROB_CHAN;
}
public void setPROB_CHAN(String PROB_CHAN) {
this.PROB_CHAN = PROB_CHAN;
}
public String getINVERSE_CHAN() {
return INVERSE_CHAN;
}
public void setINVERSE_CHAN(String INVERSE_CHAN) {
this.INVERSE_CHAN = INVERSE_CHAN;
}
public String getWAV_POINT_MODE() {
return WAV_POINT_MODE;
}
public void setWAV_POINT_MODE(String WAV_POINT_MODE) {
this.WAV_POINT_MODE = WAV_POINT_MODE;
}
public String getDISPLAY_CHAN() {
return DISPLAY_CHAN;
}
public void setDISPLAY_CHAN(String DISPLAY_CHAN) {
this.DISPLAY_CHAN = DISPLAY_CHAN;
}
public String getENABLE_CHAN_BWL_OFF() {
return ENABLE_CHAN_BWL_OFF;
}
public void setENABLE_CHAN_BWL_OFF(String ENABLE_CHAN_BWL_OFF) {
this.ENABLE_CHAN_BWL_OFF = ENABLE_CHAN_BWL_OFF;
}
public String getCOUPLING_CHAN() {
return COUPLING_CHAN;
}
public void setCOUPLING_CHAN(String COUPLING_CHAN) {
this.COUPLING_CHAN = COUPLING_CHAN;
}
public String getOFFSET_NUMBER() {
return OFFSET_NUMBER;
}
public void setOFFSET_NUMBER(String OFFSET_NUMBER) {
this.OFFSET_NUMBER = OFFSET_NUMBER;
}
public String getWAV_FORM() {
return WAV_FORM;
}
public void setWAV_FORM(String WAV_FORM) {
this.WAV_FORM = WAV_FORM;
}
public void Loadfichier() throws FileNotFoundException{
try {
System.out.println(Yaml.loadType(new File("config.yml"), Loadyml.class));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String toString() {
//dso1072B.setchanconftest(commande);
// Float.parseFloat(SCALE_NUMBER);
return "[Commande SCPI='"+WAV_FORM+","+ENABLE_CHAN_BWL_OFF+""
+ ","+TRIG_EDGE_LEV+","+TIM_MODE+""
+ ","+SCALE_NUMBER+","+TRIG_EDGE_SLOP+""
+ ","+DISPLAY_CHAN+","+TIM_MAIN_SCAL+""
+ ","+SCALE_CHAN+","+TRIG_EDGE_SOURCE+""
+ ","+WAV_SOUR+","+INVERSE_CHAN+""
+ ","+PROB_CHAN+","+WAV_POINT_MODE+""
+ ","+ENABLE_CHAN_OFFSET+","+COUPLING_CHAN+""
+ ","+OFFSET_NUMBER+"']";
}
}
How can i fix that ?
Console screen
To solve your issue - use double instead of float - Somewhere inside Jyaml's codebase it tries to match floating point numbers to getter/setter methods (not fields) of type double reflectively. As your field is of type float, reflection based matching fails and you get the default value of 0.0f
On a side note :
Use Boxed/object versions of fields and methods, i.e. - Double instead of double. null make more sense than 0.0 for existence check. (I'd also recommend java 8's Optional).
Jyaml is super old and its codebase looks horrendous , please consider using a newer alternative for yaml parsing, preferably one that uses annotations like Jackson.
With Jackson - use annotations to map names in yaml file as they are and keep your code according to java conventions ( fields and methods should be camel cased)
I've created this method and I'm unsure why it says there's a missing return statement. do I need to change the print to a return? (it's the method at the very bottom) I'm a bit of a Java beginner so any help will be appreciated!
public class Book {
private String title;
private String author;
private int copies;
private boolean borrowed;
public Book( String inAuthor, String inTitle, int inNumberOfCopies ) {
this.author = inAuthor;
this.title = inAuthor;
this.copies = inNumberOfCopies;
}
public void borrowed() {
borrowed = true;
}
public void rented() {
borrowed = true;
}
public void returned() {
borrowed = false;
}
public boolean isBorrowed() {
return borrowed;
}
public String getAuthor() {
return this.author;
}
public static String getTitle() {
return getTitle();
}
public int getTotalCopies() {
return this.copies;
}
public int getAvailableCopies() {
}
public void withdrawCopy() {
int found = 0;
for (Book b : Library.getListOfBooks()) {
if (b.getTitle().equals(title)) {
if (found == 0) {
found = 1;
}
if (!b.isBorrowed()) {
b.borrowed=true;
found = 2;
break;
}
if (found == 0) {
System.out.println("Sorry, this book is not in our catalog.");
} else if (found == 1) {
System.out.println("Sorry, this book is already borrowed.");
} else if (found == 2) {
System.out.println("You successfully borrowed " + title);
}
}
}
}
public String returnCopy() {
boolean found = false;
for (Book book : Library.getListOfBooks()) {
if (getTitle().equals(title) && book.isBorrowed()) {
book.returned();
found = true;
}
if (found) {
System.out.println("you successfully returned " + title);
}
}
}
}
public String returnCopy()
String after public means that this method will return a String.
Your public String returnCopy() is currently not returning anything.
If you don't want to return anything, you can use void like this:
public void returnCopy(){
// code
}
Same issue with public int getAvailableCopies(), this is supposed to return an int but you are not returning anything.
Be careful:
this method:
public static String getTitle() {
return getTitle();
}
is a recursive method without a base condition. This will cause an error and force your application to crash.
You've defined the method as returning a String but you don't return a value anywhere in the method body. Simplest fix is probably to change the return type to void...
public void returnCopy() {...
}
All the above answer are pointing to the same issue, you have defined methods that are breaking the contract about what they return..
In you code you have as well something like this:
public int getAvailableCopies() {
}
so you are telling the compiler, you have a method with the name getAvailableCopies, it takes no params and return an integer.
BUT if you don't return anything, then you are contradicting your own method, your own contract, this is an enough reason for a compiler to complain...
Conclusion:
keep in mind the information that defines the method.
I'm trying to figure out why i keep getting the error that my AM class does not override abstract method. In my teachers UML diagram it only shows that i need the equals (Object o) method in my parent radio class. Also i'm not declaring it as abstract in my abstract class.
public abstract class Radio implements Comparable
{
double currentStation;
RadioSelectionBar radioSelectionBar;
public Radio()
{
this.currentStation = getMin_Station();
}
public abstract double getMax_Station();
public abstract double getMin_Station();
public abstract double getIncrement();
public void up()
{
}
public void down()
{
}
public double getCurrentStaion()
{
return this.currentStation;
}
public void setCurrentStation(double freq)
{
this.currentStation = freq;
}
public void setStation(int buttonNumber, double station)
{
}
public double getStation(int buttonNumber)
{
return 0.0;
}
public String toString()
{
String message = ("" + currentStation);
return message;
}
public boolean equals (Object o)
{
if (o == null)
return false;
if (! (o instanceof Radio))
return false;
Radio other = (Radio) o;
return this.currentStation == other.currentStation;
}
public static void main(String[] args)
{
Radio amRadio = new AMRadio();
System.out.println(amRadio);
Radio fmRadio = new FMRadio();
System.out.println(fmRadio);
Radio xmRadio = new XMRadio();
System.out.println(xmRadio);
}
}
public class AMRadio extends Radio
{
private static final double Max_Station = 1605;
private static final double Min_Station = 535;
private static final double Increment = 10;
public AMRadio()
{
currentStation = Min_Station;
}
public double getMax_Station()
{
return this.Max_Station;
}
public double getMin_Station()
{
return this.Min_Station;
}
public double getIncrement()
{
return this.Increment;
}
public String toString()
{
String message = ("AM " + this.currentStation);
return message;
}
}
You have to implement the compareTo() method, given that Radio implements the Comparable interface and a concrete implementation for this method wasn't provided in the Radio class, so you have two choices:
Implement compareTo() in all of Radio's subclasses
Or implement compareTo() in Radio
Something like this, in AMRadio:
public int compareTo(AMRadio o) {
// return the appropriate value, read the linked documentation
}
Or like this, in Radio:
public int compareTo(Radio o) {
// return the appropriate value, read the linked documentation
}