首页 > 解决方案 > 为什么在 Android ContentProvider 中我不能使用像 'this' 这样的上下文而不是 getContext()

问题描述

    public boolean onCreate() {
      Context context = getContext();
      mDbHelper = new DbHelper(context);
      return true;
   }

    public boolean onCreate() {
      mDbHelper = new DbHelper(this);        // why this not work?
      return true;
   } 

为什么我不能使用像'this'这样的上下文而不是getContext()

标签: android

解决方案


通常,您可以在 Activity 或 Application 中使用“this”,因为它们可以充当上下文。

如果您的类不是从 Context 或 Activity 或 Application 扩展而来,则不能使用“this”,因为“DbHelper”构造函数需要上下文。


推荐阅读