【问题标题】:static reference from class to non-static method in data base adapter can't be done无法完成从类到数据库适配器中的非静态方法的静态引用
【发布时间】:2015-03-22 11:42:55
【问题描述】:

正如主题中的那样,我对 android 还是很陌生。我正在关注一些关于过滤文本的教程,在完成 eclipse 后给了我这个错误:

Cannot make a static reference to the non-static method tchCountriesByName(String) from the type DBAdapter

我在寻找其他示例,但在任何地方都找不到与我的案例匹配的地方。

  myCursorAdapter.setFilterQueryProvider(new FilterQueryProvider() {
         public Cursor runQuery(CharSequence constraint) {
             return new DBAdapter(list.this).fetchCountriesByName(constraint.toString()); //here's the error
         }
     });
 }

这里是它所指的方法。我尝试在代码中任何可以使用的地方放置“静态”,但我仍然无法正常工作。

 public Cursor fetchCountriesByName(String inputText) {
      Log.w(TAG, inputText);
      Cursor c = null;
      if (inputText == null  ||  inputText.length () == 0)  {
       c = db.query(DATABASE_TABLE, new String[] {KEY_ROWID,
         KEY_NAME, KEY_COUNTRY, KEY_REGION},
         null, null, null, null, null);

      }
      else {
      c = db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
         KEY_NAME, KEY_COUNTRY, KEY_REGION},
         KEY_NAME + " like '%" + inputText + "%'", null,
         null, null, null, null);
      }
      if (c != null) {
       c.moveToFirst();
      }
      return c;

     }

感谢您的意见。

【问题讨论】:

  • "我还是 android 新手" 你也是 Java 新手吗?你知道static 在 Java 中是什么意思吗?
  • 在尝试构建应用程序之前,您应该学习 Java 和 OOP 的基础知识。这是上学的第一周。
  • @Pshemo 我不需要为它创建实例,但我不知道如何调整 dbadapter 方法并使其成为静态

标签: java android static-methods


【解决方案1】:

你可以使fetchCountriesByName()方法static

public static Cursor fetchCountriesByName(String inputText) {
  // your method implementation
}

然后你必须使用该方法中的所有变量static

所以easy option 是创建该类的instance 并调用您的method

例如:

 public Cursor runQuery(CharSequence constraint) {
    return new DBAdapter().fetchCountriesByName(constraint.toString()); 
 }

重要的一点是你应该知道在哪里应该使用static,在哪里不应该使用?将static 放在没有意义的地方可能会导致问题。

编辑:您似乎是Java 的新手。当您创建DBAdapter 的实例时,不应该有使用new DBAdapter() 的参数构造函数。否则,您应该使用正确的 constructorDBAdapter

【讨论】:

  • 然后它说“不能对非静态字段db进行静态引用”来执行查询
  • @kTN 那么你可以选择我的第二个选项
  • “构造函数 DBAdapter() 未定义”当传递 contex 时不起作用我会看看传递 null 时会发生什么
  • @kTN 我为我的答案添加了更多点。这些可能会帮助您解决问题。你应该先学习Java basic。否则您可能会经常遇到此类问题。
  • 感谢您的宝贵意见。我现在正在阅读“用 Java 思考”。没错,我是新手,但我总是尝试自己找出答案,如果我做不到,我会寻求指导。问题是我浏览了所有教程,却找不到为什么它对这个人有用,而对我却不起作用。 sathishrmr.blogspot.co.il/2012/12/…。我在这个类中有一个构造函数,它在列表视图中显示来自 db 的数据,并且应该使用相同的构造函数对其进行过滤。
【解决方案2】:

要么使用 DBAdapter 的实例,要么将 fetchCountriesByName 设为静态。

【讨论】:

    【解决方案3】:

    尝试:

    return new DBAdapter().fetchCountriesByName(constraint.toString());
    

    代替:

     return DBAdapter.fetchCountriesByName(constraint.toString());
    

    【讨论】:

    • 谢谢,稍后它会要求定义它,但我想这至少比我现在能做的要多。
    猜你喜欢
    • 1970-01-01
    • 2023-04-02
    • 2011-01-17
    • 1970-01-01
    • 2013-08-02
    • 2013-01-15
    • 2015-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多