Android Error

D/error: Only the original thread that created a view hierarchy can touch its views.


0. 오류 내용


D/error: Only the original thread that created a view hierarchy can touch its views.


1. 오류 원인


해당 오류는 메인스레드에서 UI 변경을 해주지 않아서 나는 오류라고 생각한다.

예를 들면 Thread에서 UI 갱신을 해주기 위해서 이런 저런 코드를 사용하는 것과 같다.


2. 변경 전 코드


1
2
3
4
5
6
7
8
9
10
11
12
13
movieRetrofit.getSearch(
            clientId = getResourceString(R.string.naver_client_id),
            clientPw = getResourceString(R.string.naver_client_secret),
            type = "movie.json",
            query = searchWord.value!!
        ).subscribe({ movie ->
                movie!!.items.iterator().forEach {
                    searchDatas.add(it)
                    searchMovieAdapter.notifyItemInserted(searchDatas.size - 1)
                }
            }, { error -> Log.d("error", error.toString()) }
                , {  Log.d("onComplete""onComplete") }
            )
cs


3. 변경 후 코드


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
movieRetrofit.getSearch(
            clientId = getResourceString(R.string.naver_client_id),
            clientPw = getResourceString(R.string.naver_client_secret),
            type = "movie.json",
            query = searchWord.value!!
        ).subscribeOn(Schedulers.io())//subscribeOn, subscribe시에 사용할 스레드 :  Schedulers.io를 통해 비동기화 시킵니다.
            .observeOn(AndroidSchedulers.mainThread())//observer시에 사용할 스레드 : Android ui thread에서 동작
            .subscribe({ movie ->
                movie!!.items.iterator().forEach {
                    searchDatas.add(it)
                    searchMovieAdapter.notifyItemInserted(searchDatas.size - 1)
                }
            }, { error -> Log.d("error", error.toString()) }
                , {  Log.d("onComplete""onComplete") }
            )
cs


4. 결론


Rx의 subscribeOn과 observeOn을 통해서 스레드를 명시해주면 오류가 해결 됨.