2011-04-14 17 views
0

我想運行一個測試程序,允許用戶單擊按鈕並移動到不同的屏幕。我有Home(First Activity)和Away(Second Activity)類以及一個爲每個類指定佈局的xml文件。我的源代碼如下:在Home.onCreate NullPointerException

public class Home extends Activity { 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    Button create = (Button)findViewById(R.id.create); 
    create.setOnClickListener(new View.OnClickListener() { 
    public void onClick(View v) 
    { 
     Intent intent = new Intent(Home.this, Away.class); 
     startActivity(intent); 
    } 
}); 


    setContentView(R.layout.main); 
} 

} 

而且Away.java

public class Away extends Activity { 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.away); 
} 
} 

我得到一個NullPointerException在DDMS跟蹤

at Home.onCreate(line 17) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java: 2627) 

任何人看到我的代碼中任何可能導致這個?

+0

哪一條是17號線? – 2011-04-14 21:21:13

+0

對不起,它是create.setOnClickListener()新的View.OnClickListener() – korymiller 2011-04-14 21:23:05

回答

2

findViewById()遍歷在setContentView()膨脹佈局時設置的視圖層次結構。在調用setContentView()之前,您無法檢索到XML中視圖的引用。更改主頁您onCreate()方法是這樣的:

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    //Call me first 
    setContentView(R.layout.main); 

    Button create = (Button)findViewById(R.id.create); 
    create.setOnClickListener(new View.OnClickListener() { 
    public void onClick(View v) 
    { 
     Intent intent = new Intent(Home.this, Away.class); 
     startActivity(intent); 
    } 
    }); 
} 

否則,因爲有樹無意見findViewById()將返回null ......因此,請求值的ID的視圖不存在。

希望有幫助!

+0

完美,非常感謝你 – korymiller 2011-04-14 21:40:59

+0

非常感謝如果我的回答對你有幫助,請隨時接受。謝謝! – Devunwired 2011-04-15 14:24:46

0

如果findViewById呼叫不能找到你正在尋找實際的東西,它可以返回一個null對象,並引起呼叫setOnClickListener拋出NPE。你確定你有正確的ID(R.id.create)嗎?

+0

是的,我的按鈕在xml中爲Home如下

相關問題