๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

๋นˆ ๊ตฌ๋ฉ ์ฑ„์šฐ๊ธฐ

[Android] Value must be ≥ 0 / cursor.getColumnIndex()

https://stackoverflow.com/questions/69053061/android-studio-value-must-be-%E2%89%A5-0

 

Android Studio - Value must be ≥ 0

I am getting an error in Android Studio to do with my Cursor. I have the following line in my code String data = cursor.getString(cursor.getColumnIndex(columnIndex)); columnIndex is being passed in...

stackoverflow.com

 

Android Studio ์˜ Anayze > Inspect Code๋ฅผ ์‹คํ–‰ํ•˜๊ณ  ๋งŒ๋‚œ ๋นจ๊ฐ„ ์—๋Ÿฌ

Value must be ≥ 0 

 

๋ฌธ์ œ์˜ ์ฝ”๋“œ

val cursor = context.contentResolver.query(uri, null, null, null, null) ?: return null
cursor.moveToNext()
return try {
    val path: String? = cursor.getString(cursor.getColumnIndex("_data"))
    path
} catch (e: Exception) {
    null
} finally {
    cursor.close()
}

 

์Šคํƒ์˜ค๋ฒ„ํ”Œ๋กœ์šฐ ์„ ๋ฐฐ๋‹˜ ๋‹ต๋ณ€

https://developer.android.com/reference/android/database/Cursor#getColumnIndex(java.lang.String) 

 

Cursor  |  Android Developers

 

developer.android.com

 

 

Cursor ํด๋ž˜์Šค ์•ˆ ์ฝ”๋“œ ํ™•์ธ

Cursor.getString() : ์ธ์ˆ˜ ๊ฐ’ ๋ฒ”์œ„๊ฐ€ 0๋ถ€ํ„ฐ ์‹œ์ž‘ํ•œ๋‹ค.

Cursor.getColumnIndex() : ๋ฐ˜ํ™˜ ๊ฐ’ ๋ฒ”์œ„๊ฐ€ -1๋ถ€ํ„ฐ ์‹œ์ž‘ํ•œ๋‹ค.

Cursor.getColumnIndexOrThrow() : ๋ฐ˜ํ™˜ ๊ฐ’ ๋ฒ”์œ„๊ฐ€ 0๋ถ€ํ„ฐ ์‹œ์ž‘ํ•œ๋‹ค.

Cursor.getString()์˜ ์ธ์ˆ˜ ๊ฐ’์œผ๋กœ Cursor.getColumnIndex() ๋ณด๋‹ค๋Š” Cursor.getColumnIndexOrThrow()๋ฅผ ๊ถŒํ•˜๋Š” ์ง€ ์•Œ๊ฒ ๋‹ค.

 

์ˆ˜์ •

val cursor = context.contentResolver.query(uri, null, null, null, null) ?: return null
cursor.moveToNext()
return try {
    val path: String? = cursor.getString(cursor.getColumnIndexOrThrow("_data"))
    path
} catch (e: Exception) {
    null
} finally {
    cursor.close()
}