2011-06-15 34 views
0

我很困惑这两个决策树是如何不同的。我正在构建一个应用程序,需要根据从ListView中选择的位置来决定加载哪个视图。我试图将逻辑构建到单个控制器模块中,并发现switch-case将导致NullPointerException和FC,而if-else将完美工作。任何人都可以启发我为什么?我在C和C++中拥有强大的背景,并且习惯于能够轻松地将开关重新写入if-else,反之亦然。Android/Java问题。这两种决策树如何不同?

定义瓦尔:

private final int VALUEA = 0; 
private final int VALUEB = 1; 
private final int VALUEC = 2; 

开关情况下:

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; 
} 

的块上方将导致一个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{ 
} 

该版本完美的作品。第二个块是否因为一些时髦的Java范围规则而工作,该规则允许决策树的每个分支以第一个块没有的方式创建和正确初始化TextView?

+1

哪条线会抛出NPE? – 2011-06-15 05:40:54

回答

3

构造函数TextView需要Context。你不能只通过它null。相反:

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; 
} 
+0

为了扩展这个,为什么不用'TextView t;'声明它并等待在开关块中初始化它呢?另外,为什么't.findViewById()'在那里? – 2011-06-15 05:55:32

+0

第一:谢谢,是的,现在传递给构造函数的null是有意义的。我想我没有读好文档。第二:我会听取你的建议,让交换机进行初始化,它看起来更干净。第三:我是个白痴,哈哈。我在墙上撞了一会儿 - 第二个findViewById行不应该在那里。 – BlackJavaBean 2011-06-18 08:11:37

1

我猜它的线

TextView t = new TextView(null); 

这就是问题所在。将null传递给TextView构造函数是否合法?

没有看到堆栈跟踪,这只是在黑暗中刺伤。