在超类中创建对象

时间:2012-02-28 08:48:52

标签: java android

我的android项目中有一个超类继承自activity并实现所有必需的接口。然后我有三个不同的活动继承自这个超类。一旦创建了活动,我就会从所有子类初始化超类中的变量。超类方法:

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。谁能解释一下为什么会这样?

1 个答案:

答案 0 :(得分:0)

我建议你在超类中添加所有3个 Activity 构造函数,并从所有这些中调用 initiateVariables(上下文c)这个方法...可能你错过了它..