enum to be stored in DB - java

I have a enum class like this -
public enum FeedbackStatus {
#JsonProperty("unprocessed")
UNPROCESSED("unprocessed"),
#JsonProperty("arrived")
ARRIVED("arrived"),
#JsonProperty("performed")
PERFORMED("performed"),
#JsonProperty("cancelled")
CANCELLED("cancelled"),
#JsonProperty("removed")
REMOVED("removed"),
#JsonProperty("no-show")
NO_SHOW("no-show"),
#JsonProperty("cancel-at-door")
CANCEL_AT_DOOR("cancel-at-door");
private static final FeedbackStatus[] myEnumValues = FeedbackStatus.values();
private final String fieldDescription;
private FeedbackStatus(String value) {
this.fieldDescription = value;
}
public static FeedbackStatus fromString(String string) {
if (!TextUtils.isEmpty(string)) {
for (FeedbackStatus feedbackStatus : myEnumValues) {
if (feedbackStatus.getString().equalsIgnoreCase(string)) {
return feedbackStatus;
}
}
}
throw new IllegalArgumentException("No constant with text " + string + " found");
}
public String getString() {
return this.fieldDescription;
}
}
I need to store an object feedback in SQLITE database using GreneDAO but the object is a enum and hence I am unable to store it . The object is like -
private FeedbackStatus feedback;
How can I store it as String?

Use for ex. CANCELLED.value? When storing the data? There is also ENUM.toString(). You can store it as String and then wrap recovering data with String to Enum method.

You can not store enums in database as enumns are Java entity, so for enums you need to store their equivalent values either String or int etc.
You can get value of enum as below and than store it in database as Strings:
String PERFORMED = PERFORMED.value;
String CANCELLED= CANCELLED.value;
String REMOVED= REMOVED.value;
String NO_SHOW= NO_SHOW.value;
String CANCEL_AT_DOOR= CANCEL_AT_DOOR.value;
For more details of Enums see Java Docs here
So here actually your data model is ok but while saving enum in the database you just need one column with enum value, and while inserting you need to convert from enum to its string value and while reading from db, you need to build enum from that string.
Hope it helps!!

You can just serialize/deserialize it. Enums are serializable by default.

Related

Check if a String equals the name of an Enum constant

I would like to check if a given String equals any Enum constant names in my Enum class. Here is an example:
public enum Relation {
APPLE("an apple"),
BANANA("a banana");
private String value;
private Relation(String s) {
this.value = s;
}
public String getValue() {
return this.value;
}
}
My String would be:
String test = "a banana";
I want to check is the String equals any of the Enum constant names, i.e. "an apple" or "a banana":
if (test.equals(....)) {
System.out.println("You ordered a banana.");
}
So far, the examples I found all apply to checking if a String equals an Enum constant. But I want to check if the String equals any of the constant's names as defined in the parenthesis.
for (Relation relation : Relation.values()) {
if (relation.getValue().equals(string)) {
return relation;
}
}
return null;
You could use a map/ or set to store the enum values, which you would then be able to check for matching values.
This would only be useful if you wanted to do this repeatedly, and reuse the map or set. You would use the map if you wanted to get the related enum.
Map<String, Relation> map = new HashMap<>();
for (Relation relation : Relation.values()) {
map.put(relation.getValue(), relation);
}
if(map.containsKey("a banana")){
System.out.println("You ordered a banana.");
}
or as a set:
Set<String> set = new HashSet<>();
for (Relation relation : Relation.values()) {
set.add(relation.getValue());
}
if(set.contains("a banana")){
System.out.println("You ordered a banana.");
}

Replacing a string in an array, where the part of the string is an int

I have code where I have a constructor for an object with mixed data types:
public GuidedTour(String tourID, String tourDescription, double tourFee,
String tourDate, int tourSize, String tourLeader)
I need to be able to allow the user to update the tourSize.
I can search and find particular tours, but am having trouble working out how to replace a substring with an inputted int value int newTourSize.
So the code I am trying to make the replacement is:
String tourDetails;
String newDetails = tourDetails.replace(tourSize, newTourSize);
It won't let me do it, as I am using int values. I have trying parsing the int into a String.
I am stuck on how to do this, beyond putting all the values back in, the original values with the new value, I am sure it would be better to find and replace that part of the substring and write this new string into the array.
I'm floundering a bit (but have improved much since my first java questions here!)
Any help?
It seems like your class looks like this:
public class GuidedTour {
private String tourDetails;
public GuidedTour(String tourID, int tourSize) { // other arguments omitted for brevity
this.tourDetails = tourID + tourSize;
}
public String getTourDetails() {
return tourDetails;
}
}
And that you're now wondering how to change the tourSize into the tourDetails.
Well, it's easy. Don't forget about the parts of the tour details. Replace your class by something like
public class GuidedTour {
private String tourID;
private int tourSize;
public GuidedTour(String tourID, int tourSize) { // other arguments omitted for brevity
this.tourID = tourID;
this.tourSize = tourSize;
}
public String getTourDetails() {
return tourID + tourSize;
}
public void setTourSize(int newTourSize) {
this.tourSize = newTourSize;
}
}
Now you don't need to do any String replacement anymore. You just set the new tour size, and ask the GuidedTour instance to recreate the tourDetails String by reassembling all the parts.
If you just want to convert a primitive typed value to a String, do that:
String.valueOf(tourSize)
The String class contains several static methods for creating a String object from various inputs.
An addition of empty string "" using String Concatenation Operator "+" to any primitive type will result in a string. It is a equivalent operation to String.valueOf(data). For example:
String strSize = tourSize+"";

How to get an String value from another String

This could sound strange but actually is quite simple.
Short description: I have a class variable called
public static final String ACCELEROMETER_X = "AccX";
In one function I do this, which get me "ACCELEROMETER_X" from a enum (sensors is an arrayList of my enum).
for i...
columns = columns + sensors.get(i).name()
The point is I want to introduce in columns not "ACCELEROMETER_X", but "AccX". Any idea? I know I could do it using switch and cases but my enum has more than 30 values so Id rather prefer other "cleaner" way to do it.
If you want your enum constant to be replaced with that string value, a better way would be keep that string as a field in the enum itself:
enum Sensor {
ACCELEROMETER_X("AccX"),
// Other constants
;
private final String abbreviation;
private Sensor(final String abbreviation) {
this.abbreviation = abbreviation;
}
#Override
public String toString() {
return abbreviation;
}
}
And instead of:
sensors.get(i).name()
use this:
sensors.get(i).toString()
Solution 1 : If you keep the value in class
Create a Map with key as the id (ACCELEROMETER_X) and value as "AccX" and when you get the value from the Enum use that to find the value from the map using name() as the key.
Map<String, String> map = new HashMap<String,String>();
map.put("ACCELEROMETER_X","AccX");
//some place where you want value from name
map.get(enumInstance.name());
Solution 2: Change the enum (more preferable)
enum Some{
ACCELEROMETER_X("AccX");
}
In your enum add this
public String getAccelerometerX (){
return ACCELEROMETER_X ;
}
and then:
for i... columns = columns + sensors.get(i).getAccelerometerX ()
I think what you're trying to do is to get the value of a field from its name which you have in a String, if that's the case, you could do something like this:
public static final String ACCELEROMETER_X = "AccX";
// ...
Field field = MyClassName.class.getField("ACCELEROMETER_X");
String value = (String)field.get(new MyClassName());
System.out.println(value); // prints "AccX"
Of course you'll have to catch some Exceptions.

How to make sure Uniqueness of Constants values in Java Class in development phase?

Our team have a shared Java class only for Constant values
When any developer need to add a constant
He will add a record in this class
public class Constants_Class {
public static final String Constant1 = "value1";
public static final String Constant2 = "value2";
public static final String Constant3 = "value3";
// Need to prevent that in Development time - NOT Run time
public static final String Constant4 = "value1"; // value inserted before
}
The problem is that
We need in Development time prevent any developer
To add a new constant its value inserted before
// Need Unique Constants Value(s)
Any suggestions ??
You really should be using enums. This will solve the problem you're seeing.
You can also associate String values with enums:
public enum MyEnums {
Constant1("value1"),
Constant2("value2"),
Constant3("value3");
private String value;
MyEnum(String value) {
this.value = value;
}
public String getValue() {
return this.value;
}
}
Then you can do MyEnum.Constant1.getValue().
To do what you're asking at development time would require parsing the code, essentially duplicating compilation. So it makes sense to let it be compiled and create a unit test to perform your check, then set up the project so that unit test is run each time the code base is compiled. I'm pretty sure the most common unit test library in use is JUnit.
To easily check uniqueness of values, you can use the Set.add method, which returns false if the item being added already exists in the set:
#Test
public class TestConstantUniqueness() {
Set<String> stringValues = new HashSet<String>();
for (MyConstantEnum value : MyConstantEnum.values()) {
String s = value.stringValue();
Assert.assertTrue(
"More than one constant in " + MyConstantEnum.class
+ " has the string value \"" + s + "\"",
stringValues.add(s));
}
}

How can I access a field in an array, where the name of the field in stored in a variable?

I have an array of type Records[], which contains fields such as name, age, and score.
I have a method which will be will need to access one of these fields, but I won't know which.
I want to, for example, do the following:
String fieldToUse = "name";
System.out.println(myRecords[0].fieldToUse);
In this case I could switch fieldToUse to whichever field I wanted to find. This doesn't work, however - how do I do this?
Thanks in advance.
Edit: myRecords is of type Records.
This could be done using refection:
Field field = Record.class.getField(fieldToUse);
Object fieldValue = field.get(record);
Full exeample:
static class Record {
public String name;
public int age;
public Record(String name, int age) {
this.name = name;
this.age = age;
}
}
public static void main(String[] args) throws Exception {
Record[] records = new Record[2];
records[0] = new Record("David", 29);
records[1] = new Record("Andreas", 28);
System.out.println("Davids name: " + getField("name", records[0]));
System.out.println("Andreas age: " + getField("age", records[1]));
}
private static Object getField(String field, Record record) throws Exception {
return record.getClass().getField(field).get(record);
}
prints:
Davids name: David
Andreas age: 28
I think that what you need to do is impossible with Java.
With your structure, you should iterate over your Records[] and select the right one.
You may try using a HashMap<String, Record> where the String is fieldToUse.
This way you can just use something like hashmap.get(fieldToUse) to get the right Record
A possibility would be to change the interface of Records to have a getProperty() style method:
System.out.println(Records[0].getProperty(fieldToUse));
Internally, Records could use a Map implementation to store the values. Assuming name is a String, and age and score are Integers the Map would be Map<String, String>, keyed by the attribute name. Additionally, Records could provide methods for each attribute for use elsewhere that returned the appropriate type.
You can make a Map representation of type Record. With each field name as key.
Record
name: "YXZ"
age: 12
score: 657
Now store this in an array.
You can now access
Records[0].get("name");
This is the best I can think of in terms of Java.

Categories