티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

How to read/write a boolean when implementing the Parcelable interface?

Parcelable 인터페이스를 구현할 때 boolean을 읽고 쓰는 방법은 무엇입니까?

 문제 내용 

I'm trying to make an ArrayList Parcelable in order to pass to an activity a list of custom object. I start writing a myObjectList class which extends ArrayList<myObject> and implement Parcelable.

액티비티에 사용자 정의 객체 목록을 전달하기 위해 ArrayList Parcelable을 만들려고 합니다. ArrayList<myObject>를 상속하여 Parcelable을 구현하는 myObjectList 클래스 작성을 시작합니다.

 

Some attributes of MyObject are boolean but Parcel don't have any method read/writeBoolean.

MyObject의 일부 속성은 boolean이지만 Parcel에는 read/writeBoolean 메서드가 없습니다.

 

What is the best way to handle this?

이것을 처리하는 가장 좋은 방법은 무엇입니까?

 

 

 

 높은 점수를 받은 Solution 

Here's how I'd do it...

할 수 있는 방법은 다음과 같습니다..

 

writeToParcel:

Parcel에 쓰기:
dest.writeByte((byte) (myBoolean ? 1 : 0));     //if myBoolean == true, byte == 1

 

readFromParcel:

Parcel에서 읽기:
myBoolean = in.readByte() != 0;     //myBoolean == true if byte != 0

 

 

 가장 최근 달린 Solution 

Short and simple implementation in Kotlin, with nullable support:

nullable 지원이 포함된 Kotlin의 짧고 간단한 구현:

 

Add methods to Parcel

Parcel에 메소드 추가
fun Parcel.writeBoolean(flag: Boolean?) {
    when(flag) {
        true -> writeInt(1)
        false -> writeInt(0)
        else -> writeInt(-1)
    }
}

fun Parcel.readBoolean(): Boolean? {
    return when(readInt()) {
        1 -> true
        0 -> false
        else -> null
    }
}

 

And use it:

그리고 그것을 사용하세요:
parcel.writeBoolean(isUserActive)

parcel.readBoolean()        // For true, false, null
parcel.readBoolean()!!      // For only true and false

 

 

출처 : https://stackoverflow.com/questions/6201311/how-to-read-write-a-boolean-when-implementing-the-parcelable-interface

반응형
댓글
공지사항
최근에 올라온 글