[英]Getting null pointer exception that I can't figure out
I have been working on this issue for a while. 我已经在这个问题上工作了一段时间。 I keep getting a null pointer exception on the following function, the myProfile variable is a reference to another class that had been declared at the beginning as private UserProfile myProfile, where UserProfile is the original class, I believe that is where I'm running into the problem.: 我在以下函数中不断收到一个空指针异常,myProfile变量是对另一个类的引用,该类在开始时已声明为私有UserProfile myProfile,其中UserProfile是原始类,我相信这是我遇到的地方问题。:
public void saveProfile()
{
if ((myProfile!=(null)) && !(myProfile.getName().isEmpty()))
{
profiles.put(myProfile.getName(), myProfile);
}
}
If myProfile
is not null
as you said, check what myProfile.getName()
is returning using debugger. 如果myProfile
不如您所说的为null
,请使用调试器检查返回的myProfile.getName()
。 If it returns null, then you cannot call isEmpty
on a null reference. 如果返回null,则无法在null引用上调用isEmpty
。
Anywhere there's a dot ( .
), you have a possibility of a null pointer exception. 在任何有点( .
)的地方,都可能会出现空指针异常。 For example, you check that myProfile
is not null, but you don't check whether myProfile.getName()
is not null before attempting to do an .isEmpty()
on it. 例如,您检查myProfile
不为null,但是在尝试.isEmpty()
之前,不检查myProfile.getName()
是否不为null。
Likewise, if profiles
is null, you'll get a null pointer exception when calling .put()
on it. 同样,如果profiles
为null,则在对其调用.put()
时会得到null指针异常。
modify your code as follows. 如下修改您的代码。 It wont cause an exception 它不会引起异常
public void saveProfile(){
if ((myProfile!=null) && (myProfile.getName() != null) &&!(myProfile.getName().isEmpty())){
profiles.put(myProfile.getName(), myProfile);
}
}
public void saveProfile()
{
if (myProfile!=null && myProfile.getName()!=null && !myProfile.getName().isEmpty())
{
if(profiles==null)
profiles = makeAnInstanceOfProfiles();
profiles.put(myProfile.getName(), myProfile);
}
}
With test code (run with assertion enabled): 使用测试代码(在启用断言的情况下运行):
public void saveProfile()
{
assert(myProfile!=null):"null at myprofile";
assert(myProfile.getName()!=null):"null at myprofile/getName";
assert(profiles!=null) : "profiles is null";
if (myProfile!=null && myProfile.getName()!=null && !myProfile.getName().isEmpty())
{
if(profiles==null)
profiles = makeAnInstanceOfProfiles();
profiles.put(myProfile.getName(), myProfile);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.