繁体   English   中英

从 Android 中的 SQLite 获取数据时出现问题

[英]Problem with fetching data from SQLite in Android

我正在关注这个关于使用您自己的 SQLite 数据库的教程 我按照教程中的描述执行了这些步骤:

  • 准备我的数据库
  • 将相同的 EXACT DataBaseHelper class 复制到我的项目 package。 您可以在那里看到 class 代码
  • 然后,我刚刚向DataBaseHelper class 添加了一种方法,即fetchData 它只是获取具有给定名称的整个表:

     public Cursor fetchData(String table) { String[] selectionArgs = new String[] {"*"}; return myDataBase.query(table, null, null, selectionArgs, null, null, null); }
  • 之后,在我的一个活动课程中,我这样做了:

     DataBaseHelper myDbHelper; myDbHelper = new DataBaseHelper(this); try { myDbHelper.createDataBase(); } catch (IOException ioe) { throw new Error("Unable to create database"); } try { myDbHelper.openDataBase(); } catch (SQLException sqle) { throw sqle; } TextView txt = (TextView) findViewById(R.id.txt); try { //I will use my method to fetch a table named: myTable Cursor c = myDbHelper.fetchData("myTable"); if((Object)c.getCount().= null) txt.setText(c;getCount()). else txt;setText("null"). } catch(Exception e) { txt;setText("error"); }

但是,我在 TextView 中不断收到“错误”。 我的方式有问题吗?

我的问题与 SQLite 无关。 这是一个愚蠢的错误:-\

错误在这里的第二行:

if((Object)c.getCount() != null)
    txt.setText(c.getCount());

它必须是这样的:

    txt.setText(""+c.getCount());

setText()方法接受ChaSequencegetCount()方法返回不兼容类型的Integer 你可以通过添加空字符串来解决这个简单的方法:)

多谢你们。

public Cursor fetchData(String table) {
     return myDataBase.query(table, null, null, null, null, null, null);
}

似乎您对selectionArgs参数有错误的想法。 文档中,它说:

您可以在选择中包含?s,它将被 selectionArgs 中的值替换,以便它们出现在选择中。 这些值将绑定为字符串。

您尝试将 int 转换为 Object,然后将转换值与 null 进行比较。 我会说你的代码很可能会在那里中断。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM