Android Studio

Android - 다른 Activity로 데이터 전달 시 클래스의 객체를 전달하는 방법 Serializable , putExtra(), getSerializableExtra()

왕현성 2023. 2. 1. 17:49
728x90

1. Serializable (직렬화)

클래스 정의시 뒤에 implements Serializable 정의

내부에서 사용되는 객체 데이터를 외부에서도 사용 할 수 있도록 해주는 것

 

객체 자체에 여러가지 정보를 담아 다른 액티비티에게 데이터를 전달하는 방법

  • 여러가지의 데이터를 보낼 경우 하나하나 일일이 지정하지 않고 객체 자체에 정보를 담는 것이 유용
  • 예를 들면 회원가입시 회원의 정보를 일일이 지정하지 않고 객체에 담아 전달하는 것이 편리

 

public class Contact implements Serializable {

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

 

2. putExtra()

지금까지는 주석처리한 코드와 같이 3줄을 작성해야했지만, 직렬화 이후엔 1줄로 작성 가능

//                    intent.putExtra("id",contact.id);
//                    intent.putExtra("name",contact.name);
//                    intent.putExtra("phone",contact.phone);
                    intent.putExtra("contact",contact);

 

3. getSerializableExtra()

주석처리한 5줄을 3줄로 줄여 작성 가능.

//        int id = getIntent().getIntExtra("id",0);
//        String name = getIntent().getStringExtra("name");
//        String phone = getIntent().getStringExtra("phone");
//        editName.setText(name);
//        editPhone.setText(phone);
        Contact contact = (Contact) getIntent().getSerializableExtra("contact");
        editName.setText(contact.name);
        editPhone.setText(contact.phone);