简体   繁体   中英

Checking for null in if statement isn't working in java

Here is my if statement:

for(int i=0;i<SharedPrefsData.subscribers.length; i++){//loop through subscribers array
        if(SharedPrefsData.subscribers[i] == null ){//if string at index i is null
            SharedPrefsData.subscribers[i] = "";//make it empty string instead of null
        }

    }

I want it to loop through an array of strings and check if each element is null . My array is:

[name_1, null, null, null, null, null, null, null, null, null, null, null, null, null, null]

and yet it never enters the then part of my if statement. If anyone can help, it would be greatly appreciated.

My code that sets the array: 我的代码设置数组:

public static String[] getPrefs(){
    String[] ToReturn;
    String tempString = settings.getString("123", "0");
    if(tempString == "0"){
        //show some type of error
        ToReturn = null;
    } else {
        ToReturn = tempString.split("@,#");
    }
    return ToReturn;


}

And this is the statement that calls the method:

SharedPrefsData.setSubscribers(SharedPrefsData.getPrefs());

settings is a field in the same class of type SharedPreferences

The problem might be in the source of data

SharedPrefsData.subscribers array might have 'null' string instead of null. Just try

if(SharedPrefsData.subscribers[i] == null ||  SharedPrefsData.subscribers[i].equals("null"))

Again, the issue might be with the source and if the issue is resolved by above statement, you need to look at source and make sure it is not returning 'null' string in place of null object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM