Java 在超类中创建对象
我的android项目中有一个超类,它继承自activity并实现所有必要的接口。然后我有三个不同的活动继承自这个超类。创建活动后,我从所有子类初始化超类中的变量。超类方法:Java 在超类中创建对象,java,android,Java,Android,我的android项目中有一个超类,它继承自activity并实现所有必要的接口。然后我有三个不同的活动继承自这个超类。创建活动后,我从所有子类初始化超类中的变量。超类方法: protected void initiateVariables(Context c){ dm = new DisplayMetrics(); toasty = new Toast(c); customBuilder = new MyDialog.Builder(c); customDial
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。有人能解释一下为什么会这样吗?我建议您在超类中添加所有3个活动构造函数,并从所有构造函数调用initiateVariables(上下文c)此方法。。。您可能缺少它。请确保超类的方法在其构造函数中被调用。。您对“活动构造函数”是什么意思?当您继承超类的构造函数时,在当前类的构造函数执行完成之前被调用。。好的,但这对我有什么帮助?我的意思是为什么我现在的工作方式不起作用?为什么我会得到一个空指针异常?