2

I am getting a NullPointerException on the line with the 2 **, can someone explain to me why this is happening? I've also tried using a switch/case statement with no luck.

String test;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    **if(test.equals("One")) {**
        setContentView(R.layout.activity_one);
    } else if(test.equals("Two")){
        setContentView(R.layout.activity_two);
    } else {
        setContentView(R.layout.activity_main);
    }
sidgate
  • 14,650
  • 11
  • 68
  • 119
dchamb
  • 179
  • 2
  • 10

3 Answers3

1

You're getting a NPE because your String test is never initialized, so it's actually null.

On the line with the ** you're trying to invoke a method on a null reference.

if(test.equals("One")) { // Will generate NPE
    setContentView(R.layout.activity_one);
} else if(test.equals("Two")){ // Will generate NPE
    setContentView(R.layout.activity_two);
} else {
    setContentView(R.layout.activity_main);
}

You have to initialize the variable. And as a good practice you can always check for null, like:

if (test != null) {
    // do something.
}

And like it was said on other answers, you can compare the literals like:

"one".equals(test);

A suggestion would be not to use "magic numbers" and "magic strings". Declare those literals on your class, like:

private static final String STR_ONE = "One";
private static final String STR_TWO = "Two";

Then, on your if/else do the comparison like this:

if (STR_ONE.equals(test)) {
    setContentView(R.layout.activity_one);
} else if (STR_TWO.equals(test)) {
    setContentView(R.layout.activity_two);  
} else {
    setContentView(R.layout.activity_main); 
}

More info on NullPointerException here on the docs and on this question.

Community
  • 1
  • 1
Mauker
  • 11,237
  • 7
  • 58
  • 76
1

test is null and the NullPointerException is raised.

You should initialize that variable.

Moreover, it would be better when you need to check some String with a constant to put the constant variable to this object, for example change this:

if(test.equals("One"))

To this:

if("One".equals(test))

In this way you are safe even if test will be null.

antoniodvr
  • 1,259
  • 1
  • 14
  • 15
1

Your test variable is null. To avoid null checks on String it is always a good idea to have equals method called on constant value

if("One".equals(test)) {
    setContentView(R.layout.activity_one);
} else if("Two".equals(test)){
    setContentView(R.layout.activity_two);
} else {
    setContentView(R.layout.activity_main);
}
sidgate
  • 14,650
  • 11
  • 68
  • 119