備忘録 〜プログラミング〜

プログラミングに関する事をつらつらと、、

androidでsqliteを使用するとき、queryの第4引数の配列にnullが入っていたらIllegalArgumentExceptionでアプリが強制終了する問題

Androidsqliteを使用する機会があったので実装していたのですが、以下のように実装したときにアプリが強制終了する事がありました。

/*
 * データを一件取得
*/
private ResumeContentsEntity fetch(String where, String[] params) {
    SQLiteDatabase db = DB_HELPER.getReadableDatabase();
        Cursor cursor = db.query(
        TABLE_NAME,
                COLUMNS,
                where,
                params,
                null,
                null,
                null);
        cursor.moveToFirst();
        ResumeContentsEntity entity = null;
        if (cursor.getCount() != 0) {
            entity = new ResumeContentsEntity();
            entity.setId(cursor.getInt(cursor.getColumnIndex(ID)));
            entity.setProductId(cursor.getString(cursor.getColumnIndex(PRODUCT_ID)));
            entity.setContentId(cursor.getString(cursor.getColumnIndex(CONTENT_ID)));
            entity.setBitrate(cursor.getInt(cursor.getColumnIndex(BITRATE)));
            entity.setPartNo(cursor.getInt(cursor.getColumnIndex(PART)));
            entity.setResumePosition(cursor.getInt(cursor.getColumnIndex(RESUME_POSITION)));
            entity.setPlayType(cursor.getString(cursor.getColumnIndex(PLAY_TYPE)));
        }
    return entity;
}

paramsの中身を、Logを書き出してみると、以下のようになります。

0: null
1: 0
2: 0
3: stream

この最初のnullが問題でIllegalArgumentExceptionが出ていたという事です。
回避策として、paramsのnullチェックを行う事で回避しました。

boolean hasNull = false;
for(String param: params){
    if(param == null){
        hasNull = true;
    }
}
if(!hasNull) {
    cursor = db.query(
            TABLE_NAME,
                COLUMNS,
                where,
                params,
                null,
                null,
                null);
} else {
        cursor = db.query(
                TABLE_NAME,
                COLUMNS,
                where,
                null,
                null,
                null,
                null);
}

sql - Android: the bind value at index 1 is null - Stack Overflow