从SQLite表中获取价值

时间:2018-08-14 21:30:08

标签: android sqlite

我有一个名为ServerDatabaseHelper的数据库。 我正在尝试从基础

中获取价值
private DatabaseHelper db;
db = new DatabaseHelper(getActivity());
int have = db.getAxe(Column_ID);

在DatabaseHelper中的位置

public int getAxe(long id)
{
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(Server.TABLE_NAME,
            new String[]{Server.COLUMN_ID, Server.COLUMN_AXE},
            Server.COLUMN_ID + "=?",
            new String[]{String.valueOf(id)}, null, null, null, null);
    return cursor.getInt(cursor.getColumnIndex(Server.COLUMN_AXE));

}

但是我遇到运行时错误:

android.database.CursorIndexOutOfBoundsException: 
Index -1 requested, with a size of 1

如果需要,我可以提供Server代码,但我认为问题出在这里

4 个答案:

答案 0 :(得分:0)

db.query返回位于索引-1处的NonNull游标,您必须将其移动到0,如果它没有移动到0,则意味着不返回任何数据。

您必须先致电cursor.moveToNext(),然后再读取FIRST位置,再致电cursor.getInt()

if (cursor.moveToNext()) // if true it have data, otherwise a empty cursor was returned
   return cursor.getInt(cursor.getColumnIndex(Server.COLUMN_AXE));
else
   return -1;

还记得从中读取所有想要的内容后调用cursor.close(),通常是:

try {
    if (cursor.moveToNext()) // if true it have data, otherwise a empty cursor was returned
       return cursor.getInt(cursor.getColumnIndex(Server.COLUMN_AXE));
    else
       return -1;
} finally {
    cursor.close();
}

答案 1 :(得分:0)

我的数据库帮助程序类可能会为您提供帮助。 getUser函数类似于您的需求。

public class DatabaseHandler extends SQLiteOpenHelper {

private static final String TAG = DatabaseHandler.class.getSimpleName();
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_NAME = "MYDB";

private static final ReadWriteLock rwLock = new ReentrantReadWriteLock(true);

private static final String TABLE_USER = "_USER";
private static final String KEY_USER_ID = "_USER_ID";
private static final String KEY_USER_NAME = "_USER_NAME";
private static final String KEY_USER_PASSWORD = "_USER_PASSWORD";
private static final String KEY_USER_BAR = "_USER_BAR";
private static final String KEY_USER_LASTLOGIN = "_USER_LASTLOGIN";
private static final String DROP_TABLE_USER = "DROP TABLE IF EXISTS " + TABLE_USER;
private static final String CREATE_TABLE_USER = "CREATE TABLE IF NOT EXISTS "
        + TABLE_USER + " ("
        + KEY_USER_ID + " TEXT, "
        + KEY_USER_NAME + " TEXT, "
        + KEY_USER_PASSWORD + " TEXT, "
        + KEY_USER_BAR + " INTEGER NOT NULL DEFAULT 0, "
        + KEY_USER_LASTLOGIN + " TEXT)";

public DatabaseHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

private static void beginReadLock() {
    rwLock.readLock().lock();
}

private static void endReadLock() {
    rwLock.readLock().unlock();
}

private static void beginWriteLock() {
    rwLock.writeLock().lock();
}

private static void endWriteLock() {
    rwLock.writeLock().unlock();
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(DROP_TABLE_USER);
    db.execSQL(CREATE_TABLE_USER);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    onCreate(db);
}

public void clearAll() {
    SQLiteDatabase db = this.getWritableDatabase();
    onCreate(db);
}

public void clearUser() {
    SQLiteDatabase db = null;
    try {
        beginWriteLock();
        db = this.getWritableDatabase();
        db.beginTransaction();
        db.delete(TABLE_USER, null, null);
        db.setTransactionSuccessful();
        db.endTransaction();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (db != null) {
            try {
                if (db.isOpen()) {
                    db.close();
                }
            } catch (Exception ee) {
                ee.printStackTrace();
            }
            endWriteLock();
        }
    }
}

public void setUser(SignInRequestModel user, String userId) {
    SQLiteDatabase db = null;
    Date now = Calendar.getInstance().getTime();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
    String currentTime = dateFormat.format(now);
    try {
        beginWriteLock();
        db = this.getWritableDatabase();
        db.beginTransaction();
        ContentValues values = new ContentValues();
        values.put(KEY_USER_ID, userId);
        values.put(KEY_USER_NAME, user.getUsername());
        values.put(KEY_USER_PASSWORD, user.getPassword());
        values.put(KEY_USER_BAR, user.getBarId());
        values.put(KEY_USER_LASTLOGIN, currentTime);
        db.insert(TABLE_USER, null, values);
        db.setTransactionSuccessful();
        db.endTransaction();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (db != null) {
            try {
                if (db.isOpen()) {
                    db.close();
                }
            } catch (Exception ee) {
                ee.printStackTrace();
            }
            endWriteLock();
        }
    }
}



public SignInRequestModel getUser(){
    SQLiteDatabase db = null;
    SignInRequestModel requestModel = new SignInRequestModel();
    try {
        beginReadLock();
        db = this.getReadableDatabase();
        Cursor cursor = db.query(
                TABLE_USER,
                new String[]{KEY_USER_NAME, KEY_USER_PASSWORD, KEY_USER_BAR},
                null,
                null,
                null,
                null,
                KEY_USER_LASTLOGIN + " DESC",
                "1"
        );
        if (cursor != null && !cursor.isClosed()) {
            if (cursor.moveToFirst()) {
                requestModel = new SignInRequestModel(
                        cursor.getInt(cursor.getColumnIndex(KEY_USER_BAR)),
                        cursor.getString(cursor.getColumnIndex(KEY_USER_NAME)),
                        cursor.getString(cursor.getColumnIndex(KEY_USER_PASSWORD))
                );
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (db != null) {
            try {
                if (db.isOpen()) {
                    db.close();
                }
            } catch (Exception ee) {
                ee.printStackTrace();
            }
            endReadLock();
        }
    }
    return requestModel;
}


}

答案 2 :(得分:0)

请看看我对其他问题的回答

在这种情况下,我将遍历所有记录并获取最后一条记录,假设您仅返回1条记录,那么使用此代码就可以了。 如果您不想循环并且知道它总是将成为一条记录,则可以删除do while循环并仅使用cursor.moveToFirst()

public int getAxe(long id) {

    SQLiteDatabase db = this.getReadableDatabase();

    long returnId = 0;

    Cursor cursor = null;

    try {
        cursor = db.query(Server.TABLE_NAME, new String[]{Server.COLUMN_ID, Server.COLUMN_AXE}, Server.COLUMN_ID + "=?", new String[]{String.valueOf(id)}, null, null, null, null);


        if (cursor.getCount() != 0 && cursor.moveToFirst()) {
            do {

                returnId = cursor.getInt(cursor.getColumnIndex(Server.COLUMN_AXE));

            } while (cursor.moveToNext());
        }

    }catch (Exception e) {
        e.printStackTrace();
    }finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    return returnId;
}

答案 3 :(得分:0)

获得out of bounds -1的原因是,光标在第一行之前位于位置-1。您需要移动到某个位置,以便可以提取数据。

该消息还表明您在光标中有1行。

您可以使用:-

public int getAxe(long id)
{
    int rv = -1; 
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(Server.TABLE_NAME,
            new String[]{Server.COLUMN_ID, Server.COLUMN_AXE},
            Server.COLUMN_ID + "=?",
            new String[]{String.valueOf(id)}, null, null, null, null);
    if (cursor.moveToFirst()) {
        rv = cursor.getInt(cursor.getColumnIndex(Server.COLUMN_AXE));
    }
    cursor.close(); //<<<< should always close cursors when done with them
    return rv; 
}
  • 注意事项
    • 如果未找到任何行,则将返回-1(这可能适合也可能不合适)
    • 以上代码为原则代码,未经测试,可能有错误。