2011-08-21 10 views
8

こんにちは私は少しのAndroidアプリ(バージョン2.3.3)を書いています。今、私はこの非常に基本的なコードでこの奇妙にNullPointer例外を取得:findViewByIdを使用しているときにonCreate()でNullPointerExceptionが発生しました - 以前にsetContentViewが使用されていましたか?

メインmenu.xmlで、現時点では、このシンプルなレイアウトを使用して
public void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.mainmenu); 

newDeck = (Button) findViewById(R.id.newDeckB); 
loadDeck = (Button) findViewById(R.id.loadDeckB); 
viewEdition = (Button) findViewById(R.id.viewEditionB); 

newDeck.setOnClickListener(this); 
loadDeck.setOnClickListener(this); 
viewEdition.setOnClickListener(this); 
} 

イム:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:orientation="vertical" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent"> 
<Button android:id="@+id/newDeckB" 
     android:text="New Deck" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content"/> 
<Button android:id="@+id/loadDeckB" 
     android:text="Load Deck" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content"/> 
<Button android:id="@+id/viewEditionB" 
     android:text="View Edition" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content"/> 
<TextView android:id="@+id/currentDeckTextView" 
     android:text="Default Deck" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content"/> 
</LinearLayout> 

今私の問題は、ライン25でnullpointexceptionです、iはボタンnewDeckがヌルであることを考え出したデバッガを使用して第1 clickListener

newDeck.setOnClickListener(this); 

を設定ラインはあります。私はウェブで多くを検索しましたが、この種の問題に対する唯一の答えは、setContentViewがfindViewByIdの前に設定されていることを確認することでした。これは明らかにここに当てはまります。

私はどんなアドバイスでも非常にうれしいです。

Thx in Before!

+0

)(ONSTARTへのonCreate(から "findViewByID")を移動しなければならなかった 'R.id.newDeckB'は、実際にR.layout.mainmenu''に存在していますか? –

+0

私はまったく同じ問題(イライラしていました!)を持っていました。それは私のために解決したコメント(@ manelizzard)でした: '時々、あなたは "きれいにする"必要があります。 Eclipseから。 (つまり、 'onPostCreate()'を使う必要はありません!) – coco

+0

クリーンで再構築がうまくいかない。 –

答えて

10

あなたのビューを取得し、onPostCreate()メソッドでリスナーを設定します。

+0

あなたの投稿にたくさんのThx。 なぜ私は本当に理解できませんが、今は動作します。 私は、javaコードとxml(newDeckBからnewDeckButton)のid-Namesを変更しました。私はすでに昨日それを試みたので、実際にはそれを取得しないと、それは問題を解決しませんでした。 – Neuhier

+1

時には、あなたは "クリーン"とコンパイルされた正しいresurcesを得るためにプロジェクトを再構築する必要があります、それはEclipseからのものです。 onPostCreate()メソッドは、コンテンツが完全にロードされたときに実行されます。答えを受け入れる、plz =) – manelizzard

+0

あなたの説明をありがとう。 – Neuhier

-2

2つのアプリケーションが期待するイベント、のonCreate()、およびONSTART()は、あなたが問題にこの機能を入れ

どちらがあります。

私は

@Override 
protected void onStart() { 
     // use findViewById() here instead of in onCreate() 
    } 
+1

詳細情報を含めてください。 –

+0

答えをより明確に説明する必要があります。それ以外の場合は、それが正しかったとしてもあまり役に立ちません。 – JakeGould

+0

アプリケーションには、onCreate()とonStart()の2つのイベントがあります。 この関数をどの関数に入れるかは重要です。 –

関連する問題