Logan Mayes
Logan Mayes

Reputation: 1

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.:

public void saveProfile()
{
    if ((myProfile!=(null)) && !(myProfile.getName().isEmpty()))
    {
        profiles.put(myProfile.getName(), myProfile);
    }
}

Upvotes: 0

Views: 130

Answers (4)

Blessed Geek
Blessed Geek

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

Fedor Skrynnikov
Fedor Skrynnikov

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

StriplingWarrior
StriplingWarrior

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

Mahesh
Mahesh

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

Related Questions