Java Class Method Error android - android

I have a method inside of a standard Java class that takes in a String[] as a parameter and returns a String[]. Basically the method is reading the Shared Preferences and returning a String[]. Here it is:
public static String[] getPrefs(){
String tempString = settings.getString("123", "0");
if(tempString == ("0")){
//show some type of error
return null;
}
String[] ToReturn = tempString.split("#,#");
return ToReturn;
And the Error:
Here is a link to a picture with my error at line 3.
I also got an error that didn't say much other than that it was at line 4.
Before you ask, the LogCat didn't give any more info than what I just list. These are all runtime errors and eclipse doesn't detect any errors.
Thanks in advance for any help.

Change the line to
if (tempString == null) {
//show some type of error
return null;
}
This is how you check for null, not by calling .equals(). Calling .equals() (or any method) on a null object will cause a NullPointerException.
Edit: After your third edit, you need to change it to
if(tempString.equals("0")){
Since tempString will no longer default to null, as it did prior to your edit.

Related

Can anyone suggest me that below if condition is wrong or not? [duplicate]

This question already has answers here:
Check whether a String is not Null and not Empty
(35 answers)
Closed 6 years ago.
May occur any exception in coding for checking string is null or not ? Please help.
String code ;
if (!code.equals(null)) {
}
else
{
}
Here is how you can check if String value is null or not
if(code != null){
}else{
}
You can not us !code.equals(null) because, equals is used to compare same object type. null is not any object type and code is String. If you consider null as String, then you can use !code.equals("null")
String can be checked like this:
if(code.equals("null") || code.equals("")) {
// code to do when string is null.
}
else {
// code to do when string is not null.
}
equals() is use to check the similarity of two String, and == or != is use to check the condition. In your case you are checking the similarity of string.
if (!code.equals(null)) {
//code checks that String code is equal to null or not
}
else
{
}
another
if (code != null) {
//code checks if code is not equals to null (condition checking)
}
else
{
}
There are many ways to check if String is empty in Java, but what is the right way of doing it? right in the sense of robustness, performance and readability. If robustness is your priority then using equals() method or Apache commons StringUtils is the right way to do this check. If you don't want to use third party library and happy of doing null check by yourself, then checking String's length is the fastest way and using isEmpty() method from String is most readable way. By the way, don't confuse between empty and null String, if your application treat them same, then you can consider them same otherwise they are different, as null may not be classified as empty. Here are three examples of checking String is empty or not by using JDK library itself.
Read more Here
You can't use .equals(null) to make a null check, because the API description for Object#equals states that:
For any non-null reference value x, x.equals(null) should return false.
Not only would this be a useless check (since it always returns false), it would also throw a NullPointerException if code actually was null, because a null value does not define an equals method.
Object x = null;
boolean isNull = x.equals(null); // NullPointerException on .equals
The only practical way to do a null check is to use:
if (code != null) {
}
If you want to check whether string is empty i.e. null or "" then use
if(TextUtils.isEmpty(code)){
}else{
}
equals checks the value exists in string.

Android JSONObject getString method check for null/NULL?

Hitting a brick wall in my code at the moment for fetching json objects from multiple pages(using a loop) in a AsyncTask. It reaches the last page, but getting the correct if statement to ensure that the loop DOESN'T run again and continues on is baffling me.
String data = //some correct json data with next element that holds a uri parseable string
JSONObject initial = new JSONObject(data);
String next = initial.getString(nextObjSTR);
//gonna start from the "last" page and recursively return to the 1st page
if(*The if condition I need help with*) {
//there is another page
makeConnection(Uri.parse(next));
}
Basically, the last page of json elements has a next element with a null or no element value, which triggers the IOException error caught in makeConnection method because my initial if statement has always been failing.
Can I get a reason or help as to the appropriate if check for Strings from json? I've tried String != null as NullPointerExceptions occur if I use any method from String to compare. Likewise, JsonObject.NULL comparison doesn't work for me either.
None of the other answers worked, and I ended up questioning whether the element was really null despite looking at the parsed json data via an online tool. In the end, JSONObject.IsNull(element mapping name) is the right approach.
If you're sure that the value is either null (empty) or a correct URI, and assuming that the nextObjSTR key is always present in the data JSON, then that will do:
if (next != null && !next.trim().isEmpty()) {
makeConnection(Uri.parse(next));
}
Or, since you're on Android, it's better use the more convenient method:
if (!TextUtils.isEmpty(next)) {
makeConnection(Uri.parse(next));
}
You can use the optString Method of the JSONObject. If the JSON key is not this method will return a empty string, so you can check it easily:
String next = initial.optString(nextObjSTR);
if ( ! next.isEmpty() ) {
makeConnection(Uri.parse(next));
}
Source: https://developer.android.com/reference/org/json/JSONObject.html#optString(java.lang.String)
you must check value with key is has in json object.
Try below code:
JSONObject initial = new JSONObject(data);
if(initial.has(nextObjSTR)) {
String next = initial.getString(nextObjSTR);
if (next != null && !next.isEmpty()) {
makeConnection(Uri.parse(next));
}
}
I do like this...
String value;
if(jsonObject.get("name").toString.equals("null")){
value = "";
else{
value = jsonObject.getString("name");
}

android - jackson get null fields value as empty string

My JSON stream can be different each time. For example sometime it can include a "Song" field and sometime not.
I am getting this fields value asText ? How to tell Jackson to get this value as an Empty String if it is not defined ?
Example
"Content": "MusicContent",
"Song": "Track_1",
if try node.get("Song").asText() it will give "Track_1"
"Content": "MusicContent",
Now , if i try to get node.get("Song") it gives null pointer exception. I want to get an empty string when calling asText().
How can i do that ?
Thanks
You could check for null before calling the asText() on the node. i would probably do it like this :
if (node.get("Song") != null){
myString = node.get("Song").asText();
} else {
myString = "";
}
Or in a fancy way like this :
myString = ((node.get("Song")!=null) ? node.get("Song").asText() : "");

Android text string comparison

In a custom SimpleCursorAdapter, I'm trying to compare a status String, with confusing results.
My string is initialised from the cursor like this (and I've checked with toast that it contains the expected values).
String visitStatus = cursor.getString(cursor.getColumnIndex(CallData.COLUMN_VisitStatus));
visitStatus can be null, Open, Cancelled or Complete.
If I try to compare visitStatus to "any string in quotes", the app crashes with a NullPointerException. Only if I compare to null do I get anything at all - and that is no use to me
if(visitStatus.equals(null)) // the app crashes with a NullPointerException
if(visitStatus == null) // doesn't crash
if(visitStatus != null) // doesn't crash
if(visitStatus == "Complete") // doesn't crash or do anything
if(visitStatus.equals("Complete")) // the app crashes with a NullPointerException.
Basically, I can compare to null, but only in the way that isn't supposed to work. I can't compare to actual strings such as "Open" or "Complete".
I'm going slightly nuts with this, and am badly missing my C# comfort zone. This particular activity is a nightmare of listfragments, contentproviders, customadapters, viewpagers, pagertitlestrips and list row xml templates!
halp!
This is because visitStatus is null. Whenever you try to access its methods, it crashes. (That is: visitString.equals(), visitString.length(), etc., all will crash.)
However, the equality operator (==) supports null parameters on either side of it. (So, if (null == null) is a valid check.)
You should check like this:
if (visitStatus != null && visitStatus.equals("Complete")) {
// ...
}
Or, you can do "Yoda syntax" (backwards checking), which supports null parameters:
if ("Complete".equals(visitStatus)) {
// ...
}
Also, a final note: You cannot compare string contents using == (as in, you cannot do "a" == new String("a"), nor visitString == "Complete"). For a detailed explanation on that, see this Q&A thread.
String should be compared using .equals()
The NullPointerException caused because the visitStatus is null

No Such Method Exception - using Reflection

I'm trying to use reflection (on an android app) to invoke a method and it work only when I do it this way
Object impresora = loadedClass.newInstance();
Object args[] = {"00:15:0E:E0:DD:38", true};
for(Method m : impresora.getClass().getDeclaredMethods())
if("BTConnection".compareTo(m.getName()) == 0)
int resultado = (Integer) m.invoke(impresora, args);
But I don't want to iterate everytime, so I'm trying this way, but this is where I get the NoSuchMethodException
Method m = impresora.getClass().getDeclaredMethod("BTConnection");
m.invoke(impresora, args);
Thanks in advance
In your first snippet you're doing object.getClass() in your second snippet you're doing impresora.getClass().
You need the actual parameter types in order to find the methods otherwise it will try to look for the method without an argument which I am guessing doesn't exist in your class.
Seeing:
Object args[] = {"00:15:0E:E0:DD:38", true};
I am guessing that the first argument is a String and second one is a boolean, so in order to find the method you need to do the following:
Method m = c.getDeclaredMethod("BTConnection", String.class, Boolean.class);

Categories

Resources