2012-02-28 91 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