我正在开发一个安卓应用程序。我的问题是我可以在抽象类中获取应用程序上下文吗?它给了我上下文变量的空指针异常,我认为这可能是因为我在抽象类中使用它。
注意:在我的代码中,我有一个抽象类(抽象类本身扩展了 Activity),用于实例化其他类 - Activites。在抽象类中,我创建了一个活动助手的实例,一个处理应用程序中一些常见活动相关功能的类。这是我的活动助手类:
public class ActivityHelper {
protected Activity mActivity;
public static ActivityHelper createInstance(Activity activity, Context context) {
return UIUtils.isTablet(context) ?
new ActivityHelperTablet(activity) :
new ActivityHelper(activity);
}
protected ActivityHelper(Activity activity) {
mActivity = activity;
}
}
函数 isTablet 接收我在抽象类中创建的上下文变量
public static boolean isTablet(Context context) {
// Can use static final constants like HONEYCOMB, declared in later versions
// of the OS since they are inlined at compile time.
return isHoneycomb() ||
((context.getResources().getConfiguration().screenLayout &
Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE);
}
BaseActivity的重要部分:
public abstract class BaseActivity extends Activity {
Context context = this.getApplicationContext();
final ActivityHelper mActivityHelper = ActivityHelper.createInstance(this, context);
}
但它给了我一个空指针异常。所以我认为这可能是因为抽象类。这是日志:
06-12 15:59:56.011: E/AndroidRuntime(1206): Caused by: java.lang.NullPointerException
06-12 15:59:56.011: E/AndroidRuntime(1206): at
android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:101)
06-12 15:59:56.011: E/AndroidRuntime(1206): at
com.navayo.sec.voip.activities.BaseActivity.<init>(BaseActivity.java:35)
06-12 15:59:56.011: E/AndroidRuntime(1206): at
com.navayo.sec.voip.activities.MainActivity.<init>(MainActivity.java:43)
06-12 15:59:56.011: E/AndroidRuntime(1206): at
java.lang.Class.newInstanceImpl(Native Method)
06-12 15:59:56.011: E/AndroidRuntime(1206): at
java.lang.Class.newInstance(Class.java:1319)
06-12 15:59:56.011: E/AndroidRuntime(1206): at
android.app.Instrumentation.newActivity(Instrumentation.java:1023)
06-12 15:59:56.011: E/AndroidRuntime(1206): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1870)