2011-06-15 36 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構造函數是否合法?

沒有看到堆棧跟蹤,這只是在黑暗中刺傷。