본문 바로가기
  • 콩's 코딩노트
Android

Android Studio - 다른 액티비티로 데이터 전달 시, 클래스의 객체를 전달하는 방법

by Cong_S 2022. 7. 15.

Serializable, putExtra(), getSerializableExtra()

 

 

프로젝트를 진행할 때, a 액티비티에서 생성된 데이터를 b 액티비티로 전달하려한다.

이때 생각할 수 있는 방법으로는

 

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

위와 같이 putExtra로 객체에 있는 데이터의 키값을 지정하여 하나씩 보내는 방법을 생각해볼 수 있지만

데이터의 수가 많은 경우 비효율적일 뿐더러 데이터를 빼먹을 수도 있기 때문에 

클래스의 객체를 통째로 보내는 방법을 익혀둘 필요가 있다.

 

방법은 다음과 같다.

1. 우선 클래스의 객체를 별도로 정의해둔 파일에서 implements Serializable 을 작성해준다.

public class Contact implements Serializable {
    public int id;
    public String name;
    public String phone;

 

 

2. 이제 데이터를 보낼 액티비티에서 하나하나 키값을 보내는 부분을 지우고, intent.putExtra에

위에서 implements Serializable 해준 클래스 객체를 넣어준다.

// 클래스 객체 생성
Contact contact = contactList.get(index);

// 다른 액티비티로 데이터 전송
Intent intent = new Intent(context, EditActivity.class);

intent.putExtra("contact", contact);

//        데이터를 하나씩 보낼때 사용하는 방법
//        intent.putExtra("id", contact.id);
//        intent.putExtra("name", contact.name);
//        intent.putExtra("phone", contact.phone);

context.startActivity(intent);

 

 

3. 이제 데이터를 받을 액티비티 (예시 코드의 EditActivity) 에서 getSerializableExtra 메소드로 데이터를 받아주면 된다.

(Contact)의 의미는 해당 클래스 객체로 만들어달라는 캐스팅이며, 빼먹고 작성해도 에러 표시에서 바로 생성할 수 있다.

// 다른 액티비티에서 넘어온 데이터가 있으면 먼저 받아준다. (Contact)는 캐스팅. 해당 클래스 객체로 만들어달란 의미.
contact = (Contact) getIntent().getSerializableExtra("contact");


// 데이터를 하나씩 가져왔을 때, 데이터를 받아주는 코드
//        int id = getIntent().getIntExtra("id", 0);
//        String name = getIntent().getStringExtra("name");
//        String phone = getIntent().getStringExtra("phone");

 

댓글