【问题标题】:Can't add parameter 'this'无法添加参数“this”
【发布时间】:2017-05-09 02:34:54
【问题描述】:

它在 MainAcitvity.class 中有效,但在 QueryUtils.class 中无效。

private WeatherDBHelper weatherDBHelper = new WeatherDBHelper(this); 

【问题讨论】:

  • 将所有这些都包含为文本,而不是图像。图片对我们毫无用处。
  • 请包含完整的编译错误。

标签: java android sqlite


【解决方案1】:

确保WeatherDBHelper构造函数接收上下文作为参数

Public class WeatherDBHelper{
     Context context;
     public WeatherDBHelper(Context context){
         this.context = context;
     }
     ....
}

编辑

WeatherDBHelper 只接收 Context 作为参数。 QueryUtils 没有 Context 类型。

可以在QueryUtils类中添加上下文的地方完成

Context context;
private WeatherDBHelper weatherDBHelper;
public QueryUtils(Context context){
     this.context = context;
     weatherDBHelper = new WeatherDBHelper(context); 
}

在 MainActivity 中使用

QueryUtils qt = new QueryUtils(this);

【讨论】:

  • WeatherDBHelper 没有问题,因为private WeatherDBHelper weatherDBHelper = new WeatherDBHelper(this); MainActivity 工作
【解决方案2】:

你的类 QueryUtilis 应该 扩展 SQLiteOpenHelper

【讨论】:

    【解决方案3】:

    问题是WeatherDBHelper 需要一个Context 对象,而QueryUtils 不是Context 类型,所以this 在这里不起作用。

    MainActivity 中可以成功使用this 的原因是MainActivityActivity,它是Context 的子类。这是它的对象层次结构:

    java.lang.Object 
    ↳
        android.content.Context 
        ↳
            android.content.ContextWrapper 
            ↳
                android.view.ContextThemeWrapper 
                ↳
                    android.app.Activity
    

    所以,在MainActivity 中,this 指的是一个实际上是Context 的对象。在QueryUtils 中没有。

    您实际上需要将Context 传递给此。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-26
      • 2021-09-27
      • 1970-01-01
      • 2016-08-18
      • 1970-01-01
      • 1970-01-01
      • 2013-02-05
      相关资源
      最近更新 更多