2011-06-15 24 views
0

私はこれら2つの決定木がどのように異なっているかについて非常に混乱しています。私はListViewから選択された位置に基づいてロードするビューを決定する必要があるアプリケーションを構築しています。私は、単一のコントローラモジュールにロジックを構築しようとしましたが、if-elseが完全に動作する間、switch-caseがNullPointerExceptionとFCを引き起こすことがわかりました。なぜ誰かが私に啓発することができますか?私はCとC++で強力な背景を持っており、if-elseとその逆にスイッチを簡単に書き直すことに慣れています。Android/Javaの質問。これら2つの決定木はどのように異なっていますか?

定義VARS:

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(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{ 
} 

。 2番目のブロックは、デシジョンツリーの各ブランチが最初のブロックが作成しない方法でTextViewを作成して適切に初期化できるような、ファンキーなJavaスコープ規則のために機能しますか?

+1

どのラインがNPEをスローしますか? –

答えて

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()'行がそこにありますか? –

+0

最初に:ありがとう、ええ、コンストラクタに渡されたnullは今意味があります。私は十分にドキュメントを読んでいないと思う。 2番目:私はあなたの助言を取り、スイッチが初期化を行うようにします。それはそのようにきれいに見えます。 第三:私はばかだ、ハハだ。私はしばらく壁に頭を叩いていた - 第2のfindViewByIdラインはそこにあるはずではなかった。 – BlackJavaBean

1

私はそれが問題だライン

TextView t = new TextView(null); 

だ推測しています。 TextViewコンストラクタにnullを渡すことは合法ですか?

スタックトレースを見ることなく、これは暗闇の中でのスタブです。

関連する問題