Android/Java: Enum methods crashing app - java

My enum declaration:
public enum Note { A, A_SHARP, B, C, C_SHARP, D, D_SHARP,
E, F, F_SHARP, G, G_SHARP;
public String toString(Note note) {
if (note == Note.A)
return "A";
else if (note == Note.A_SHARP)
return "A#";
else if (note == Note.B)
return "B";
else if (note == Note.C)
return "C";
else if (note == Note.C_SHARP)
return "C#";
else if (note == Note.D)
return "D";
else if (note == Note.D_SHARP)
return "D#";
else if (note == Note.E)
return "E";
else if (note == Note.F)
return "F";
else if (note == Note.F_SHARP)
return "F#";
else if (note == Note.G)
return "G";
else if (note == Note.G_SHARP)
return "G#";
else
return "";
}
public Note getNext() {
int index = ordinal();
index++;
if (index > values().length)
return values()[0];
else
return values()[index];
}
}
Whenever I call either of these two methods, my app crashes. Here is where I call them:
public void ChangeSound(View v) {
note = note.getNext();
tvSounds.setText(note.toString(note));
}
ChangeSound() is an onClick method for a button. If I remove both lines in ChangeSound(), the code works as it should, but if either of the two lines are in there, the app crashes on the button click. Any ideas why? Thanks in advance!!
EDIT**
note is a variable of type Note
Thank you everyone! It was returning null (look at Jason C's answers (my comment)). All of this was helpful for me!

You should use >= since probably you're getting some OutOfBoundsException
if (index >= values().length)
return values()[0];
else
return values()[index];
}
Also instead of switch you could sth like that:
public enum Note { A("A"), A_SHARP("A#"), B("B");
private String s;
public Note (String s) {
this.s = s;
}
public String toString() {
return s;
}

Change this:
if (index > values().length)
to this:
if (index >= values().length)

It's unclear what you mean by "crashes", and you also do not show enough context (what is 'note'?) but the most likely cause based on the fact that you stated either of those two lines crash seems to be that 'note' is null. If 'note' is null then ChangeSound will throw a NullPointerException. You need to make sure that if ChangeSound is assuming 'note' is not null, that that is actually the case.
Also you should make toString(Note) a static method, and define a non-static toString() override. This will give Note.toString(Note) the ability to handle nulls correctly:
public static String toString (Note n) {
return n == null ? "" : n.toString();
}
Edit: As noted in other answers, you should use >= instead of > (even == would be sufficient), that is also a potential problem.

The issue has already been spotted by the other answers. Note however that you could simplify your code in two ways:
by associating the String representation of the notes with the enum constants directly
by using a modulus instead of your if/else in getNext
It could look like:
public enum Note { A("A"), A_SHARP("A#"), B("B"), C("C"), C_SHARP("C#"), D("D"),
D_SHARP("D#"), E("E"), F("F"), F_SHARP("F#"), G("G"), G_SHARP("G#");
private final String noteName;
Note(String noteName) {
this.noteName = noteName;
}
#Override
public String toString() {
return noteName;
}
public Note getNext() {
int nextIndex = (ordinal() + 1) % values().length;
return values()[nextIndex];
}
}
And in your main code:
note = note.getNext();
tvSounds.setText(note.toString());

Related

Does java have some convention to indicate that object is in empty state?

Of course, empty definition can differ. I'm used to PHP's empty though, which calls empty everything that evaluates to false. I'd like to call these things empty in my Java application:
null
String of zero length
0 Integer, Float or Double
false
Any array of zero length
Empty ArrayList or HashMap
Java has, for example, toString convention. Every object is granted to give you some string representation. In my Settings class I operate with HashMap<String, Object>. My empty method looks now like this:
public boolean empty(String name) {
Object val = settings.get(name);
if(val!=null) {
return false;
}
return true;
}
I'd like to extend it in a conventional manner, rather than if(val instanceof XXX) chain.
No, there is no standard convention for this in Java. Also, in Java there is no such thing as "evaluate to false" (except for booleans and Booleans, of course).
You will have to write a method (or rather, a series of overloaded methods for each type you need it for) which implements your notion of "empty". For example:
public static boolean isEmpty(String s) {
return (s == null) || (s.isEmpty());
}
public static boolean isEmpty(int i) {
return i == 0;
}
...
You could use overloading to describe all the "empty" objects:
public static boolean empty(Object o) {
return o == null;
}
public static boolean empty(Object[] array) {
return array == null || array.length == 0;
}
public static boolean empty(int[] array) { //do the same for other primitives
return array == null || array.length == 0;
}
public static boolean empty(String s) {
return s == null || s.isEmpty();
}
public static boolean empty(Number n) {
return n == null || n.doubleValue() == 0;
}
public static boolean empty(Collection<?> c) {
return c == null || c.isEmpty();
}
public static boolean empty(Map<?, ?> m) {
return m == null || m.isEmpty();
}
Examples:
public static void main(String[] args) {
Object o = null;
System.out.println(empty(o));
System.out.println(empty(""));
System.out.println(empty("as"));
System.out.println(empty(new int[0]));
System.out.println(empty(new int[] { 1, 2}));
System.out.println(empty(Collections.emptyList()));
System.out.println(empty(Arrays.asList("s")));
System.out.println(empty(0));
System.out.println(empty(1));
}
AFAIK there is no such convention. It's fairly common to see project specific utility classes with methods such as:
public static boolean isEmpty(String s) {
return s == null || s.isEmpty();
}
However I personally think its use is a bit of a code smell in Java. There's a lot of badly written Java around, but well written Java shouldn't need null checks everywhere, and you should know enough about the type of an object to apply type-specific definitions of "empty".
The exception would be if you were doing reflection-oriented code that worked with Object variables who's type you don't know at compile time. That code should be so isolated that it's not appropriate to have a util method to support it.
Python's duck-typing means the rules are sort of different.
How about creating an interface EmptinessComparable or something similar, and having all your classes implement that? So you can just expect that, and not have to ask instanceof every time.
Java does not, but Groovy does. Groovy runs on the Java VM alongside Java code and provides many shortcuts and convenient conventions such as this. A good approach is write foundation and crital project components in Java and use Groovy for less critical higher level components.
If you want to use the one approach, I would overload a utility method:
public class MyUtils {
public static boolean isEmpty(String s) {
return s == null || s.isEmpty();
}
public static boolean isEmpty(Boolean b) {
return b == null || !b;
}
// add other versions of the method for other types
}
Then your code always looks like:
if (MyUtils.isEmpty(something))
If the type you're checking isn't supported, you'll get a compiler error, and you can implement another version as you like.
There are ways to establish the notion of emptiness but it's not standardized across all Java classes. For example, the Map (implementation) provides the Map#containsKey() method to check if a key exists or not. The List and String (implementations) provide the isEmpty() method but the List or String reference itself could be null and hence you cannot avoid a null check there.
You could however come up with a utility class of your own that takes an Object and using instanceof adapts the empty checks accordingly.
public final class DataUtils {
public static boolean isEmpty(Object data) {
if (data == null) {
return false;
}
if (data instanceof String) {
return ((String) data).isEmpty();
}
if (data instanceof Collection) {
return ((Collection) data).isEmpty();
}
}
}
The Guava Libraries already contains Defaults class that do just that.
Calling defaultValue will return the default value for any primitive type (as specified by the JLS), and null for any other type.
You can use it like shown below:
import com.google.common.base.Defaults;
Defaults.defaultValue(Integer.TYPE); //will return 0
Below is example code on how to use it:
import com.google.common.base.Defaults;
public class CheckingFieldsDefault
{
public static class MyClass {
private int x;
private int y = 2;
}
public static void main() {
MyClass my = new MyClass();
System.out.println("x is defualt: " + (my.x == Defaults.defaultValue(box(my.x).TYPE)));
System.out.println("y is defualt: " + (my.y == Defaults.defaultValue(box(my.y).TYPE)));
}
private static <T extends Object> T box(T t) {
return t;
}
}

May I get Null pointer exception from this routine?

I have written a below routine in Java, I need to know that the code is Null Pointer Safe or not:
public class TRM_Fields {
public static String returnActualValue(String Staffing_Event,
String CurrentValue, String PriorValue) {
String returnValue;
returnValue = null;
if ("TRM".equalsIgnoreCase(Staffing_Event) && CurrentValue == null
&& PriorValue != null && !"".equalsIgnoreCase(PriorValue)) {
returnValue = PriorValue;
} else {
returnValue = CurrentValue;
}
return returnValue;
}
}
Any of the parameter Staffing_Event, CurrentValue and PriorValue may be null.
If it is not Null Pointer Safe what should I do to achieve that?
Your method is safe. You are correctly using "constantString".equals(someObject) to ensure a null-safe comparison.
Some other comments:
Your method is hard to read because you are using TitleCase for Java variables, when they should be camelCase.
You only have two possible return values. So you can simplify your method as follows:
public static String returnActualValue(String staffingEvent,
String currentValue, String priorValue) {
if ("TRM".equalsIgnoreCase(staffingEvent) && currentValue == null
&& priorValue != null && !"".equalsIgnoreCase(priorValue)) {
return priorValue;
} else {
return currentValue;
}
}
Note that the else construct isn't necessary, so it's a matter of style whether you include that structure or simply have return currentValue;.

Method is not returning String?

Doing some beginner problems for Java:
Given two strings, append them together (known as "concatenation") and return the result.
However, if the concatenation creates a double-char, then omit one of the chars, so "abc" and "cat" yields "abcat".
My code:
public static String conCat(String a, String b) {
//abc (c) == cat (c)
if (a.substring(a.length()-1,a.length()) == b.substring(0,1)) {
//return (ab) + (cat)
return a.substring(0,a.length()-2) + b;
//cat (c) == abc (c)
} else if(b.substring(0,1) == a.substring(a.length()-1,a.length())) {
//return (abc) + (at)
return a + b.substring(2,b.length());
} else if (a.equals("") || b.equals("")) {
return a + b;
}
}
I don't understand why Eclipse can't recognise the String returns.
First of all, you are comparing Strings with ==, which compares them by reference. This means that equal Strings might not return true. To avoid this problem, always use .equals() to compare Strings.
Second, keep in mind that your if statements are checked in the order specified. Since you want to check for empty strings first, you should put that one on top.
Third, you have to return something on all codepaths. If all of the if statements are false, you don't return anything. If you add else return a + b; you should get the desired behavior.
Furthermore, I suggest using a slightly different approach:
public static String conCat(String a, String b) {
//If either String is empty, we want to return the other.
if (a.isEmpty()) return b;
else if (b.isEmpty()) return a;
else {
//If the last character of a is the same as the first character of b:
//Since chars are primitives, you can (only) compare them with ==
if (a.charAt(a.length()-1) == b.charAt(0))
return a + b.subString(1);
//Otherwise, just concatenate them.
else
return a + b;
}
}
Note that you can omit the else blocks, since return will end the execution of the method there, so this will also work:
public static String conCat(String a, String b) {
if (a.isEmpty()) return b;
if (b.isEmpty()) return a;
if (a.charAt(a.length()-1) == b.charAt(0)) return a + b.subString(1);
return a + b;
}
actually, it can. but all your return statements are depending on a condition, so there 'll be cases for which you haven't provided a return statement.
in those cases, the method won't return anything, even while it should return a String.
add:
return "";
or
return null;
to the end of your method and try again.

Replacing if else with OO aproach

Lets say I have:
if (count <= instance.getFCount()) {
//do something and return String
} else if (count <= instance.getFSCount()) {
//do something and return String
} else if (count <= instance.getTCount()) {
//do something and return String
} else if (count <= instance.getOCount()) {
//do something and return String
}
I am thinking how can I replace this code into something more object oriented. The problem is that if I would have statement like this:
if (count <= 0) {
//do something and return String
} else if (count <= 1) {
//do something and return String
} else if (count <= 2) {
//do something and return String
} else if (count <= 3) {
//do something and return String
}
I could replace it with some factory pattern or enum based approach because my values 0, 1, 2, 3 would always be static. For e.g. I would create a map to hold the class against the number, then if my count is 0 I would know that I need to create an instance from the class which was mapped with zero and so on.
But now I am thinking if there is any way to be done if I don't have the static values in if condition, because for e.g. what is returned to this: instance.getOCount() might be different depending on the configuration.
Could you give me some thoughts how to achieve this?
When you have lots of different if else statements, you can employ a Strategy Pattern. This helps you create manageable code that conforms to the best practice.
I believe there's no need to replace such a simple logic with a design pattern, it's not justified. A switch would be an improvement (assuming count is an integer), but why create a bunch of classes? it'd be justified only if each one had additional, different behavior.
If you use a NavigableMap such as a TreeMap, the keys being your thresholds and values being Callables, you'll be able to retrieve the appropriate Callable and invoke it, all in a one-liner. The relevant method is NavigableMap#ceilingEntry.
final NavigableMap<Integer, Callable<String>> strats = new TreeMap<>();
...
return strats.ceilingEntry(val).getValue().call(args);
I don't think using patterns is the solution here...everything will be harder to read than your original code. But if you are sure, this is one option:
Lets say your instance belongs to a class User. Create an interface
public interface IDynamicAction<T> {
boolean select(T t);
String action(T t);
}
Make a list
List<IDynamicAction<User>> actions = new ArrayList<IDynamicAction<User>>();
actions.add(new IDynamicAction<User>() {
#Override
public boolean select(User instance) {
return count <= instance.getFSCount();
}
#Override
public String action(User t) {
System.out.println("count <= instance.getFSCount()");
return "count <= instance.getFSCount()";
}
});
actions.add(new IDynamicAction<User>() {
#Override
public boolean select(User instance) {
return count <= instance.getTCount();
}
#Override
public String action(User t) {
System.out.println("count <= instance.getTCount()");
return " count <= instance.getTCount()";
}
});
actions.add(new IDynamicAction<User>() {
#Override
public boolean select(User instance) {
return count <= instance.getOCount();
}
#Override
public String action(User t) {
System.out.println("count <= instance.getOCount()");
return " count <= instance.getOCount()";
}
});
And execute your code with
for(IDynamicAction<User> action : actions){
if(action.select(instance)){
String s = action.action(instance);
System.out.println(s);
break;
}
}
Notice the break, I'm assuming based in your code only one action can execute
If you don't need a return value you may use an abstract class instead of an interface and make the if(select) action(); a part of the AbstractDynamicAction class the code will be nicer
Java7 does not really help doing that kind of stuff. Closures would make this things easier on the eye...but IMHO, your original multiple IF is the way to go.

Best way to check NULL for objects in Java

I have a solution to check NULL values extracted from object, However i feel there might be best approach than i am doing here. So please suggest me the best ways with code snippet :)
I will be passing my xml Content to unmarshalling method & then pass the unmarshalledValues to null check method (i.e ValidateInputFiled )
Contents unmarshalledValues = unmarshalingContent( xml );
inputCheck = ValidateInputField( unmarshalledValues );
I have a POJO for my XML elements as mentioned below,
#XmlRootElement( name = "contents" )
public class Contents
{
#XmlElement
String A;
#XmlElement
String B;
#XmlElement
String C;
#XmlAttribute
String D;
public String getA()
{
return A;
}
public String getB()
{
return B;
}
public String getC()
{
return C;
}
public String getD()
{
return D;
}
}
I have defined ValidateInputFiled as mentioned below
public Boolean ValidateInputField( Contents unmarshalledValues )
{
int checker = 0;
Boolean listCheck = false;
// Extracting unmarshalled values from xml
String A= unmarshalledValues.getA();
String B= unmarshalledValues.getB();
String C = unmarshalledValues.getC();
String D= unmarshalledValues.getD();
if ( A== null || A.isEmpty() )
{
checker++;
}
if ( B== null || B.isEmpty() )
{
checker++;
}
if ( C== null || C.isEmpty() )
{
checker++;
}
if ( D== null || D.isEmpty() )
{
checker++;
}
if ( checker == 0 )
{
listCheck = true;
}
return listCheck;
}
Here i am looking to avoid NULL check for each String Values ( i.e A, B, C, D ) instead can i just do null check for Contents or for unmarshalledValues using collection or list ?
public static boolean isNullOrEmpty(String a) {
return a == null || a.isEmpty();
}
Call that for each value. You may want to think about adding them all to a list and then iterating through them, incrementing checker if they're !isNullOrEmpty to save code bloat if you have lots for fields.
PS: Make your fields private to preserve encapsulation.
pps: don't bother with a seperate boolean just return checker == 0; to keep the code neat.
Is that what you are looking for ?
public Boolean ValidateInputField(Contents unmarshalledValues) {
// Extracting unmarshalled values from xml
String A = unmarshalledValues.getA();
String B = unmarshalledValues.getB();
String C = unmarshalledValues.getC();
String D = unmarshalledValues.getD();
return checkNull(A, B, C, D);
}
private static boolean checkNull(String... strings) {
for (String string : strings) {
if (string == null || string.isEmpty()) {
return false;
}
}
return true;
}
I use the apache commons StringUtils library for this type of thing. It has a check that includes null or empty spaces, plus other combinations depending on how you treat empty spaces. Pretty much code like Jeff here gave you, but i like having other methods they include.
You can also avoid nulls alltogether by coding your getters to return "" if a value == null. Then you would not have to check each field for null.
commons-lang has a Validate class you could use:
Validate.notNull( unmarshalledValues.getA() );
Non-reflective solution for Java 8, without using a series of if's, would be to stream all fields and check for nullness:
return Stream.of(id, name).allMatch(Objects::isNull);
This remains quite easy to maintain while avoiding the reflection hammer. This will return true for null attributes.

Categories

Resources