【问题标题】:Android SQLite fetch user_idAndroid SQLite 获取 user_id
【发布时间】:2015-03-28 19:41:44
【问题描述】:

如何从 sqlite 数据库中获取 user_id?

我有一个这样创建的用户表(只是一个简单):

private static final String CREATE_TABLE_USER =
    "CREATE TABLE " + TABLE_USER +
                "("+
                COLUMN_USER_ID + " integer primary key autoincrement," +
                COLUMN_USER + " TEXT NOT NULL, " +
                COLUMN_PASSWORD + " TEXT NOT NULL" +
                ");";

我想在整个应用程序中获取用户信息(使用共享首选项)。

在我的登录页面,我只有 2 个文本字段:usernamepassword。我可以将这些值保存为变量,并将它们放入我的 createSession(String name, String email, Long userId) 方法中。但是,由于我没有 user_id 文本字段,因此我无法获取 createSession() 方法所需的 user_id ..。

public void createSession(String name, String email, Long userId){

        // Storing name in pref
        editor.putString(KEY_NAME, name);

        // Storing password in pref
        editor.putString(KEY_PASSWORD, email);

        //Storing user id in pref
        editor.putLong(KEY_ID, userId);

        // commit changes
        editor.commit();
    }

我尝试进行查询以接收 ID,并将其返回到登录页面(它将被放入 createSession() 方法中)

public Long getUserId(String username, String password) throws SQLException
{
    Cursor mCursor = database.rawQuery("SELECT user_id FROM user WHERE username=? AND password=?", new String[]{username,password});
    if (mCursor != null) {
        if(mCursor.getCount() > 0)
        {
           Long userId = mCursor.getLong(1);
        }
    }
    return null;
}

但它不会为我获取 userId .. 有人建议为什么会这样吗?

【问题讨论】:

  • 您忘记移动到第一条记录。现在你指向记录 -1。

标签: android sqlite


【解决方案1】:

您忘记将光标移动到第一条记录。现在它指向记录-1

所以改变这个

if (mCursor != null) {

到这里

if (mCursor != null && mCursor.moveToFirst()) {

而且... 1 列不存在。

改变

Long userId = mCursor.getLong(1);

Long userId = mCursor.getLong(0);

【讨论】:

  • 这可能会导致 NullPointerException。认为您的意思是 && 不是 ||
  • 感谢您的回复,我现在收到以下错误;从有 1 行 1 列的 CursorWindow 读取第 0 行第 1 列失败。
  • @jgm 是的,&&,正确。今天有点累了;)
  • 或者(只是为了更正您的代码之前):Long userId = mCursor.getLong(0);
猜你喜欢
  • 2017-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-09
  • 1970-01-01
相关资源
最近更新 更多