Reputation: 1
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.:
public void saveProfile()
{
if ((myProfile!=(null)) && !(myProfile.getName().isEmpty()))
{
profiles.put(myProfile.getName(), myProfile);
}
}
Upvotes: 0
Views: 130
Reputation: 21684
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);
}
}
Upvotes: 0
Reputation: 5609
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);
}
}
Upvotes: 1
Reputation: 156748
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.
Likewise, if profiles
is null, you'll get a null pointer exception when calling .put()
on it.
Upvotes: 1
Reputation: 34665
If myProfile
is not null
as you said, check what myProfile.getName()
is returning using debugger. If it returns null, then you cannot call isEmpty
on a null reference.
Upvotes: 3