Facebook for Android error on getting gender of user - android

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.

Related

Firestore - why my empty field is not empty?

I stumbled across a very strange error while I was doing my application. There is a function where on button click user can delete the whole Firestore documents AND the corresponding file from Storage. I store the whole URL for the picture in a string field inside the documents - but this url can be empty and this is my problem. I check if this URL field is null but somehow my code manages to skip this logical statement and tries to delete the file and that's where I get a nice nullpointer exception.
docRef = fStore.collection("ActiveJobs").document(docID);
docRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if (documentSnapshot.exists()) {
if (documentSnapshot.getString("jobPictureUrl") != null || documentSnapshot.get("jobPictureUrl) != null) {
String pictureUrl = documentSnapshot.getString("jobPictureUrl");
storageRef = fStorage.getReferenceFromUrl(pictureUrl);
storageRef.delete();
}
}
}
});
As you can see I do check if this field is empty or not in two different ways but somehow this statement always returns that it's not empty and my storageRef line gets a nullpointer exception, because the pictureUrl above IS empty. I tried to check if pictureUrl is empty, but still got the same error...
This is how I store the empty string field
Hope you can help me out and thanks for reading this!
jobPictureUrl field is not a null member. It's an empty String.
So, you have to check whether the String is empty; but currently you are doing null check.
if (!documentSnapshot.getString("jobPictureUrl").isEmpty()) {
}
isEmpty() - Returns true if, and only if, string length() is 0

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

Categories

Resources