๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ“ฑ| Android/โœ… | ์—๋Ÿฌํ•ด๊ฒฐ

[Android, Kotlin] java.lang.ClassCastException: activity cannot be cast to interface ํ•ด๊ฒฐ

by immgga 2022. 6. 7.

์˜ค๋Š˜์˜ ์˜ค๋ฅ˜๋Š” ํด๋ž˜์Šค ๊ฐ„์˜ ์บ์ŠคํŒ…์ด ์ž˜ ๋˜์ง€ ์•Š์•˜์„๋•Œ ๋ฐœ์ƒํ•˜๋Š” ์—๋Ÿฌ์ธ ClassCastException์„ ํ•ด๊ฒฐํ–ˆ๋˜ ๊ณผ์ •์„ ํฌ์ŠคํŒ… ํ•ด๋ณด๊ฒ ๋‹ค.

 

์—๋Ÿฌ ๋ณธ๋ฌธ

 

FreeBoardFragment 111๋ฒˆ์งธ ์ค„

override fun onAttach(context: Context) {
    super.onAttach(context)

    try {
        postImageData = activity as PostImageData
    } catch (e: ClassCastException) {
        Log.e("ERROR", e.printStackTrace().toString(), e.cause)
    }
}

 

interface๋ฅผ ์ด์šฉํ•ด fragment์—์„œ activity๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ์ „๋‹ฌํ•˜๋Š” ๊ณผ์ •์—์„œ onAttach ๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜๊ฒŒ ๋˜๋Š”๋ฐ, ์ด ๋ถ€๋ถ„์—์„œ ์˜ค๋ฅ˜๊ฐ€ ๋‚ฌ์—ˆ๋‹ค.

 

ํ•ด๊ฒฐํ–ˆ๋˜ ๋ฐฉ๋ฒ•

override fun onAttach(activity: Activity) {
    super.onAttach(activity)

    try {
        Log.d("SUCCESS", "onAttach: success")
        postImageData = activity as PostImageData
    } catch (e: ClassCastException) {
        Log.e("ERROR", e.printStackTrace().toString(), e.cause)
    }
}

onAttach์˜ ์ƒ์„ฑ์ž ๋ถ€๋ถ„์„ context ์—์„œ activity๋กœ ๋ณ€๊ฒฝํ•ด ์ฃผ์—ˆ๋‹ค.

728x90