I'm very confused as to how these two decision trees are different. I'm building an app that needs to decide which view to load based on the position selected from a ListView. I've tried to build the logic into a single controller module and found that the switch-case will cause a NullPointerException and FC while the if-else will work perfectly. Can anyone enlighten me as to why? I've got a strong background in C and C++ and am used to being able to easily re-write switches to if-else's and vice versa.
Defined vars:
private final int VALUEA = 0;
private final int VALUEB = 1;
private final int VALUEC = 2;
Switch-case:
TextView t = new TextView(null);
switch(value){
case VALUEA:
setContentView(R.layout.valuealayout);
t = (TextView) findViewById(R.id.valuealayout);
t.findViewById(R.id.valuealayout);
break;
case VALUEB:
setContentView(R.layout.valueblayout);
t = (TextView) findViewById(R.id.valueblayout);
t.findViewById(R.id.valueblayout);
break;
case VALUEC:
setContentView(R.layout.valueclayout);
t = (TextView) findViewById(R.id.valueclayout);
t.findViewById(R.id.valueclayout);
break;
default:
break;
}
The block above will cause a NullPointerException.
If-else:
if(value == VALUEA ){
setContentView(R.layout.valuealayout);
TextView t = (TextView) findViewById(R.id.valuealayout);
t.findViewById(R.id.valuealayout);
}else if(value == VALUEB){
setContentView(R.layout.valueblayout);
TextView t = (TextView) findViewById(R.id.valueblayout);
t.findViewById(R.id.valueblayout);
}else if(value == VALUEC){
setContentView(R.layout.valueclayout);
TextView t = (TextView) findViewById(R.id.valueclayout);
t.findViewById(R.id.valueclayout);
}else{
}
This version works perfectly. Does the second block work because of some funky Java scoping r开发者_Go百科ule that allows each branch of the decision tree to create and properly initialize the TextView in a way that the first block doesn't?
The TextView
constructor requires a Context
. You can't just pass it null
. Instead do:
TextView t = null;
switch(value){
case VALUEA:
setContentView(R.layout.valuealayout);
t = (TextView) findViewById(R.id.valuealayout);
t.findViewById(R.id.valuealayout);
break;
case VALUEB:
setContentView(R.layout.valueblayout);
t = (TextView) findViewById(R.id.valueblayout);
t.findViewById(R.id.valueblayout);
break;
case VALUEC:
setContentView(R.layout.valueclayout);
t = (TextView) findViewById(R.id.valueclayout);
t.findViewById(R.id.valueclayout);
break;
default:
break;
}
I'm guessing it's the line
TextView t = new TextView(null);
that's the problem. Is it legal to pass null to the TextView
constructor?
Without seeing the stack trace this is just a stab in the dark.
精彩评论