2012-02-28 49 views
0

我的android項目中有一個超類繼承了活動並實現了所有必需的接口。然後我有三個不同的活動從這個超類繼承。一旦創建活動,我將從所有子類的超類中初始化變量。超類方法:在超類中創建對象

protected void initiateVariables(Context c){ 
    dm = new DisplayMetrics(); 
    toasty = new Toast(c); 
    customBuilder = new MyDialog.Builder(c); 
    customDialog = new Dialog(c); 
    customProgress = new MyProgressDialog(c); 
    getWindowManager().getDefaultDisplay().getMetrics(dm); 
    screenWidth = dm.widthPixels; 
    screenHeight = dm.heightPixels; 
} 

從子類我做的:

protected void initiateVariables(Context c) { 
    super.initiateVariables(c); 
    bFavorite = (Button) findViewById(R.id.bFavorite); 
    bSetting = (Button) findViewById(R.id.bSettings); 
    bCompass = (Button) findViewById(R.id.bCompass); 
    bDeparture = (Button) findViewById(R.id.bDeparture); 
    bInfo = (Button) findViewById(R.id.bInfo); 
    bBack = (Button) findViewById(R.id.bBack); 
    bDeparture2 = (Button) findViewById(R.id.bForward); 
    bAdd = (Button) findViewById(R.id.bAdd); 
    tvHeader = (TextView) findViewById(R.id.tvHeaderText); 
    flipp = (ViewFlipper) findViewById(R.id.viewFlipper); 
    colorBackground = (RelativeLayout) findViewById(R.id.homeBackground); 
    dbList = (ListView) findViewById(R.id.dbList); } 

在我的子類onCreate方法:

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.home); 
    initiateVariables(this); 
} 

當我嘗試使用已在超被初始化的任何對象我得到一個nullpointerexception。任何人都可以向我解釋爲什麼這是?

+0

確保超類的方法在其構造函數中被調用.. – ngesh 2012-02-28 08:51:52

回答

0

我建議你添加的所有超3 活動建設者和調用initiateVariables(上下文C)這個方法從所有的人......可能是你缺少它..

+0

你如何使用活動構造函數? – user1163392 2012-02-28 09:00:01

+0

當你繼承超類的構造函數時,在你現在的類的構造函數執行完成之前調用它.. http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html – ngesh 2012-02-28 09:03:17

+0

好的,但是這對我有什麼幫助?我的意思是爲什麼我目前的做法不行?爲什麼我會得到一個空指針異常? – user1163392 2012-02-29 09:34:27