programing

Android 및 SQLite를 사용하여 데이터베이스에서 부울 가져오기

bestcode 2022. 9. 19. 23:46
반응형

Android 및 SQLite를 사용하여 데이터베이스에서 부울 가져오기

Android에서 SQLite 데이터베이스의 부울 필드 값을 얻으려면 어떻게 해야 합니까?

나는 주로 사용한다.getString(),getInt(), 등, 필드의 값을 취득할 수 있지만, 그 값은 존재하지 않는 것 같습니다.getBoolean()방법.

그 이유는 다음과 같습니다.

boolean value = cursor.getInt(boolean_column_index) > 0;

SQLite에 bool 데이터 유형이 없습니다.이 효과를 얻으려면 0 또는 1로 수정한 int를 사용합니다.SQLite 3.0의 데이터 유형 참조를 참조하십시오.

boolean value = (cursor.getInt(boolean_column_index) == 1);

이 답변의 대부분은 숫자로 표시됩니다.FormatExceptions 또는 "operator is defined for types null, int" (int를 저장한 컬럼에도 null을 유지할 수 있는 경우)이 작업을 수행하는 적절한 방법은

Boolean.parseBoolean(cursor.getString(booleanColumnIndex));`

단, 현재는 0 또는 1이 아닌 "true" 및 "false" 문자열만 저장할 수 있습니다.

Ormlite Cursor에 있는 구현에서도 Null이 확인되지만 다른 응답에서는 Null이 확인되지 않습니다.

   public boolean getBoolean(int columnIndex) {
        if (cursor.isNull(columnIndex) || cursor.getShort(columnIndex) == 0) {
            return false;
        } else {
            return true;
        }
    }

를 사용할 수도 있습니다.

boolean value =cursor.getString(boolean_column_index).equals("True");

다른 옵션

boolean value = (cursor.getString(column_index)).equals("1");

boolean에서 데이터 유형을 사용할 수 없습니다.Cursor.

결과를 얻을 수 있습니다.int그래서 그것을 변환해야 합니다.int에 대한 가치.boolean.

다음 중 하나를 사용할 수 있습니다.

boolean b = cursor.getInt(boolean_column_index) > 0;

또는

boolean b = (cursor.getInt(boolean_column_index) != 0);

부울 b = (cursor.getInt(cursor.getColumnIndex("항목"))!= 0);

그건 아주 간단해요.

public boolean getBooleanState(SQLiteDatabase db){
    boolean result = false;
    try{
        String QUERY = "SELECT " + BOOLEAN_DATA + " FROM " + TABLE_NAME + " WHERE " + ID + " = 1";
        Cursor cursor = db.rawQuery(QUERY, null);
        if (cursor.moveToFirst()){
            if(cursor.getString(0).equalsIgnoreCase("1")){
                result = true;
            }
        }
        c.close();
    }catch(Exception ee){
        Log.e(TAG, "err getBooleanState: " + TABLE_NAME );
    }
    return result;
}

옵션(nullable) 부울이 다음과 같이 저장되는 경우:INTEGER, Kotlin 확장자를 작성할 수 있습니다.

fun Cursor.getBoolean(columnIndex: Int): Boolean? {
    return if (isNull(columnIndex))
        null
    else 
        getInt(columnIndex) != 0
}

다음과 같이 사용합니다.

val value: Boolean? = cursor.getBoolean(boolean_column_index)

내가 사용하던 거야:

    val work = Work()
    work.id = cursor.getInt(0)
    work.date = cursor.getString(1)
    work.work_value = cursor.getFloat(2)
    work.place = cursor.getString(3)
    work.wind = cursor.getFloat(4)
    work.isCompetition = cursor.getInt(5) > 0
    return work

언급URL : https://stackoverflow.com/questions/4088080/get-boolean-from-database-using-android-and-sqlite

반응형