android - 从数据库中的列获取值

标签 android mysql sqlite android-cursor

我从数据库中的“threadid”列获取值。问题是它从上一条记录/行获取值。当我尝试获取第一条记录时,我的应用程序崩溃了,如何解决这个问题,问题是什么?

long id;
long threadid = datasource.getthreadid(id);
Toast.makeText(getActivity(), String.valueOf(threadid), Toast.LENGTH_SHORT).show();

public long getthreadid(long id)
  {

      String ide=String.valueOf(id);
      String queryz = "SELECT " + MySQLiteHelper.COLUMN_THREADID 
                + " FROM " + MySQLiteHelper.TABLE_NAME 
                + " WHERE " + MySQLiteHelper.COLUMN_ID + "=" + ide;
      Cursor cursor = database.rawQuery(queryz, null);
      cursor.moveToFirst();
     // cursor.moveToPosition(Integer.parseInt(String.valueOf(id)));
     long threadid= cursor.getLong(cursor.getColumnIndex("threadid"));

      cursor.close();
    return threadid;

  }

最佳答案

如果您只期望一行。那么做这样的事情可能会有用。

long threadid;

if (cursor.moveToFirst())
{
    threadid = cursor.getLong(cursor.getColumnIndex("threadid"));
}
else
{
    // ah oh, we do not have this id!
    // do something here if you need to
}

此外,如果您要使用字符串,我建议您绑定(bind)参数。我知道你已经提前很久了,但是对于字符串你可以这样做。

  String queryz = "SELECT " + MySQLiteHelper.COLUMN_THREADID 
            + " FROM " + MySQLiteHelper.TABLE_NAME 
            + " WHERE " + MySQLiteHelper.COLUMN_ID + " = ?";
  Cursor cursor = database.rawQuery(queryz, new String[]{ide});

关于android - 从数据库中的列获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18775710/

相关文章:

php - 如何找到用户之间的联系,创建一个封闭的 friend 圈?

database - 在我的 ListView 中选择项目后,滚动 Kotlin 时随机选择其他项目

ios - 获取持久协调器时核心数据奇怪崩溃

android - 代码中解析 "?android:attr/selectableItemBackground"的值

Android缩放位图图像

java - 第一次执行夜间模式代码时,会触发当前重启

android - 泛型方法在将其作为参数传递时不会识别泛型类型

mysql - node-mysql 仅在两个表合并后提供第一个表的数据

mysql - 在mysql中选择最后一个不同的记录

c++ - 虚幻引擎4.21.2和Squareys CISQLite3插件编译问题