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
Related
I print the fotonew key and it sends a null value. But if urlfoto is empty or not, if (urlfoto! = Null &&! Urlfoto.equals (" ")) goes to this section. Normally he should go to else. The urlfoto value goes to the part with a full urlfoto value in the case of null but if else. I want to check if the key I pulled is empty or full.
SharedPreferences sharedPrefNew = getContext().getSharedPreferences("sharedPref",Context.MODE_PRIVATE);
urlfoto = sharedPrefNew.getString("fotonew", "");
if(urlfoto!= null && !urlfoto.equals(""))
{
...
}
else {
System.out.println("boş");
...
}
You already declared default value of SharedPreference on Code.
urlfoto = sharedPrefNew.getString("fotonew", "");
This means if "fotonew" is empty or null sharedPrefNew returns a value ""
this line:
sharedPrefNew.getString("fotonew", "")
is responsible for taking value from shared pref. First parameter is a key, second one is a default value that will be returned if key is not found.
In your case, if there is no object stored for key "fotoNew" an empty string will be returned.
You can return null :
sharedPrefNew.getString("fotonew", null);
Hope that helps.
Check below code
if (sharedPrefNew.getString("fotonew", "") != null && !sharedPrefNew.getString("fotonew", "").isEmpty()){
//your code here
}
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.
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");
}
I have an array column called "Roots" in a user class from parse.com and I want to retrieve the array object from the column and then extract the values (strings) to an array in my application.
ParseUser.logInInBackground(user, password, new LogInCallback() {
public void done(ParseUser user, ParseException e) {
if (user != null) {
// Hooray! The user is logged in.
startMenu();
String[] testStringArray = (String[])user.get("Roots");
I'm not sure if the last line even works. Even if it does, I'm not sure how to extract the individual elements and set them to a local array that I can call on using an index e.g.
String myString = testStringArray[1]
Or some such. I have tried a few variations of the above code and I think I am missing something fundamental. Does anyone have an example of how I can accomplish this?
Thanks in advance!
Use an ArrayList<String> instead of String[], then you can access it as you would any other ArrayList object.
ArrayList<String> testStringArrayList = (ArrayList<String>)user.get("Roots");
String myString = testStringArrayList.get(1);
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() : "");