【问题标题】:SimpleCursor Adapter - Cannot use this in Static ContextSimpleCursor 适配器 - 不能在静态上下文中使用它
【发布时间】:2014-02-13 16:58:53
【问题描述】:

各位资深程序员,

我在我的 databasehandler.java 中遇到无法使用它的运行时错误。有没有什么地方可以解决这个问题。

主要活动

public class DatabaseActivity extends Activity {

    TextView idView;
    EditText productBox;
    EditText quantityBox;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_database);
        idView = (TextView) findViewById(R.id.productID);
        productBox = (EditText) findViewById(R.id.productName);
        quantityBox = (EditText) findViewById(R.id.productQuantity);
        ListView listContent = (ListView) findViewById(R.id.listView1);

        Cursor cursor = MyDBHandler.queueAll();
        startManagingCursor(cursor);

        String[] from = new String[]{MyDBHandler.COLUMN_PRODUCTNAME};
        int[] to = new int[]{R.id.text1};

        SimpleCursorAdapter cursorAdapter =
         new SimpleCursorAdapter(this, R.layout.rolypoly, cursor, from, to);

        listContent.setAdapter(cursorAdapter);

    }

MyDBHandler.java

public static Cursor queueAll(){
    String[] columns = new String[]{COLUMN_ID, COLUMN_PRODUCTNAME,COLUMN_QUANTITY};
    SQLiteDatabase db = **this**.getReadableDatabase();
    Cursor cursor = db.query(TABLE_PRODUCTS, columns,
      null, null, null, null, null);
}

【问题讨论】:

  • 请提供整个 MyDBHandler 类以查看如何以及从何处获取数据库。

标签: java android static-methods simplecursoradapter


【解决方案1】:

是的,因为错误清楚地表明您不能在静态方法中使用thisthis 指的是“当前调用”对象,因为 static 不与任何对象绑定,您不能在静态上下文中使用 this。引用自 Oracle 教程:

在实例方法或构造函数中,this 是对当前对象的引用——正在调用其方法或构造函数的对象

而不是这个:

this.getReadableDatabase();

你可以这样做来访问getReadableDatabase();

new YourClassName().getReadableDatabase();

【讨论】:

  • 尊敬的先生,感谢您的反馈,我不明白添加新的 YourClassName().getReadableDatabase() 是什么意思,您能解释一下吗?谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-10
  • 1970-01-01
  • 2019-03-17
  • 2011-11-30
相关资源
最近更新 更多