2017-07-27 67 views
0

在我的Android應用我有2個佈局使用viewFlipper的Android viewFlipper導致NullPointerException異常

<?xml version="1.0" encoding="utf-8"?> 
    <ViewFlipper xmlns:android="http://schemas.android.com/apk/res/android" 
     android:orientation="vertical" android:layout_width="match_parent" 
     android:id="@+id/switching" 
     android:layout_height="match_parent"> 

      <include layout="@layout/activity_login"/> 
      <include layout="@layout/content_team_choose"/> 
      <include layout="@layout/waiting"/> 
    </ViewFlipper> 

<?xml version="1.0" encoding="utf-8"?> 
<ViewFlipper xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" android:layout_width="match_parent" 
    android:id="@+id/switch_game" 
    android:layout_height="match_parent"> 

    <include layout="@layout/main_game"/> 
    <include layout="@layout/chat"/> 
</ViewFlipper> 
在我的拳頭活動

創建有機會獲得這樣的

protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.switching); 
     viewFlipper = (ViewFlipper) findViewById(R.id.switching); 

//some other code which triggers the change of the view, 
//like a onClickListener 

        viewFlipper.setDisplayedChild(1); 
視圖

,這工作正常。在我的第二個活動中,如果我嘗試訪問另一個視圖鰭狀肢,並且我執行vievFlipper.setDisplayedChild(1)將引發NullPointerExcption。所以我試了

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.switch_game); 
    viewFlipper = (ViewFlipper) findViewById(R.id.switch_game); 
    if(viewFipper == null) 
     Log.d("ViewError", "the viewFlipper is null"); 

和日誌出現,但我不明白爲什麼只有在這種情況下視圖爲空。 我甚至嘗試在第二個活動中獲得佈局「切換」,這也給了我相同的問題。

編輯。 NullPointerException由viewFlipper.setDisplayedChild(1)引發; 試圖訪問佈局的孩子,但我不知道,如果只有兒童是空或全部viewFlipper,所以我tryied代碼的最後部分,驗證整個佈局爲null

+0

請檢查的setContentView佈局是正確的R.layout.main_game – Meenal

+0

我還沒有注意到的第一和第二碼之間的矛盾,但我已經tryied替代「R.layout.main_game 「與」R.layout.switch_game「);」並沒有什麼能僞裝的 – DeNasti

回答

2

當應用程序嘗試使用具有空值的對象引用時,引發NullPointerException。

一個ViewFlipper主要用在情況下,當我們需要一個視圖轉換爲另一種。

viewFlipper = (ViewFlipper) findViewById(R.id.switch_game); 
+1

是的,對不起,我在最後一部分中有點混淆。 NullPointerException引發嘗試訪問佈局的子項,但我不確定是否只有兒童是null或所有viewFlipper,所以我嘗試了代碼的最後一部分,驗證整個佈局爲空 – DeNasti

相關問題