개발/안드로이드

Android - 객체 전달을 위한 Serializable

웅'jk 2023. 2. 1. 17:48

지금까지 Intent를 통한 데이터 전달은 기본 데이터 타입들로 보냈습니다.

 

객체를 보내고 싶을 때 사용하는 Serializable을 알아봅시다.

 

Serializable 은 직렬화를 의미합니다.

직렬화는 자바에서 사용된 데이터 또는 클래스를 바이트코드로 변환시키는 작업을 의미하며

이 바이트코드를 다시 데이터 또는 클래스로 변경하는 방법을 역 직렬화라고 합니다.

 

따라서 Intent를 통한 데이터 전달은 이 직렬화를 통해 바이트코드로 변환되고 이 바이트 코드를 다시 역직렬화를 통해 객체로 전달하게 됩니다.

 

JAVA code 

// Contact class 
// Serializable을 구현합니다.
public class Contact implements Serializable {

    public String name;
    public String phone;
    public int id;


    public Contact(String name , String phone){
        this.name = name;
        this.phone=phone;
    }


    public Contact(int id, String name, String phone) {
        this.name = name;
        this.id = id;
        this.phone = phone;
    }
}

Contact 클래스의 Serializable을 구현합니다.

 public ViewHolder(@NonNull View itemView) {
            super(itemView);
            txtname = itemView.findViewById(R.id.txtname);
            txtphone = itemView.findViewById(R.id.txtphone);
            imgdelete = itemView.findViewById(R.id.imgdelete);
            cardView = itemView.findViewById(R.id.cardview);

            cardView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // 1. 인텐트에 유저가 누른 이름과 전화번호를 변수에 담는다.
                    // RecyclerView의 몇번째 행인지를 알수있는 getAdapterPosition()함수!
                    int id = getAdapterPosition();
                    Contact contact = contactList.get(id);

                    // 2. 수정 액티비티를 띄운다.
                    Intent intent = new Intent(context,EditActivity.class);
                    intent.putExtra("contact", contact);
                    context.startActivity(intent);
                }
            });
        }

intent.putExtra 함수로 Cotact 변수 contact를 전달하게 됩니다.

// 받아온 데이터를 다시 객체로 만든다 -> 역직렬화
Intent intent = getIntent();
Contact contact = (Contact) intent.getSerializableExtra("contact");

이제 이 코드를 역직렬화 하는 방법은 Intent의 getSerializableExtra()함수로 가능하며 반드시 원래의 객체로 형변환을 해주셔야 합니다.