Android text string comparison - android

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

Related

multiple check or,and in if statement

hi i'm wonder why my if always Toast me : "names Successfully saved!"
i'm try every thing.
public void btnSave_Clicked(View view) {
TextView txtOname = (TextView)findViewById(R.id.txtOname);
TextView txtXname = (TextView)findViewById(R.id.txtXname);
String X = txtXname.getText().toString();
String O = txtOname.getText().toString();
if((X!="") && (O!="")){
DatabaseHelper.insertName(getBaseContext(),((TextView)findViewById(R.id.txtOname))
.getText().toString());
DatabaseHelper.insertName(getBaseContext(),((TextView)findViewById(R.id.txtXname))
.getText().toString());
Toast.makeText(this,"names Successfully saved!",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this,"E",Toast.LENGTH_SHORT).show();
}
}
}
Strings are reference types in Java, and thus the reference of a dynamically created empty string will be different from your variables. Another option to isEmpty is equals.
if (!x.equals("") && !o.equals(")) {
//code
}
Though I'd probably go with isEmpty
Replace your if statement with:
if (!x.isEmpty() && !o.isEmpty()) {
//code
}
operator == compares Object reference.
.equals() compares String value.
.isEmpty() return true if String length is 0.
Strings are objects. Object instances (the value behind them) have to be compared manually with a method to assure that the content is the same.
The == operator just compares the string references ("adresses"). So when you create 2 object instances at runtime, they have different adresses even if the content is the same. Compile-time strings on the other hand are internalized, they are put into special memory and duplicates are sorted out.
System.out.println(new String("test") == new String("test"));
This will print false, because those 2 objects get created at runtime. The new keyword in the first example mandates that a new object with a new adress is created.
System.out.println("test" == "test");
This will print true, because they are String literals, which are known at runtime, you are not explicitly stating the new keyword here either. You are simply specifying that you want those literals represented in the code somehow, so the compiler internalizes them.

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");
}

Facebook for Android error on getting gender of user

Some users are getting a force close when signing up with Facebook in our app. We received this stacktrace on the lines below:
java.lang.StringIndexOutOfBoundsException: length=0; regionStart=0; regionLength=1
at java.lang.String.startEndAndLength(String.java:588)
at java.lang.String.substring(String.java:1475)
at com.yolify.android.Activity_Splash$7.onCompleted(Activity_Splash.java:483)
at com.facebook.Request$1.onCompleted(Request.java:281)
at com.facebook.Request$4.run(Request.java:1666)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5146)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:732)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
at dalvik.system.NativeStart.main(Native Method)
Code:
String gender = user.getProperty("gender") == null ? "" : user.getProperty("gender").toString();
String Gender = gender == null ? "" : gender.substring(0,1).toUpperCase(Locale.ENGLISH)+gender.substring(1);
The force close happens on the second line of the code. Since that happens in about 1 in 100 signups, we can't reproduce the issue. If the gender is not null then what is it?
"If the gender is not null then what is it?" : it probably is null but you turn it into an empty string. Then an IndexOutOfBoundsException comes from trying to do substring(1) on that empty string.
The problem is the way you have used two back-to-back ternary operations.
The first ternary operation
String gender = user.getProperty("gender") == null ? "" : user.getProperty("gender").toString()
Is basically saying
if(user.getProperty("gender") == null){
gender="";
}
else{
gender=user.getProperty("gender").toString();
}
So far so good.
The second ternary operation (This is where it gets confusing. I dont know why you wrote 'String Gender'; I think you should replace with 'gender')
String Gender = gender == null ? "" : gender.substring(0,1).toUpperCase(Locale.ENGLISH)+gender.substring(1)
Is basically saying
if(gender == null){
gender = ""; //gender instead of String Gender
}
else{
gender = gender.substring(0,1).toUpperCase(Locale.ENGLISH) + substring(1)
}
Note that the first condition is always false because of the first ternary operation. Basically the second ternary operation will ALWAYS throw that IndexOutOfBoundsException in the event someone used a facebook account with null gender because your first ternary operation makes an empty string and your second ternary operation is trying to get a substring of that empty string. An easy way to test this is to create a new fb account and not fill in the gender and then sign into your app.
The fix: I tend to avoid ternary operations like the plague because even though they saves lines of code, its easy to get confused especially when you have two back to back that deal with the same variables. I would replace the 2nd ternary operation with
if(gender != "") { // Gender exists
gender = gender.substring(0,1).toUpperCase(Locale.ENGLISH);
}
else{
// gender us "" so do whatever
}
Thats the "most correct way" I could think of handling this. You could also try just getting rid of the +substring(1) in the second ternary operation and that would get rid of the error but thats not what I recommend.

Java Class Method Error 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.

Categories

Resources