简体   繁体   English

在if语句中检查null是否在Java中不起作用

[英]Checking for null in if statement isn't working in java

Here is my if statement: 这是我的if语句:

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 . 我希望它遍历字符串数组并检查每个元素是否为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语句的then部分。 If anyone can help, it would be greatly appreciated. 如果有人可以提供帮助,将不胜感激。

EDIT: 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 settings是与SharedPreferences类型相同的类中的一个字段

The problem might be in the source of data 问题可能出在数据源中

SharedPrefsData.subscribers array might have 'null' string instead of null. SharedPrefsData.subscribers数组可能具有'null'字符串,而不是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 同样,问题可能出在源上,如果通过上述声明解决了该问题,则需要查看源,并确保它没有返回“ null”字符串代替null对象

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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