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.