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");
'Android' 카테고리의 다른 글
Android Studio - TextWatcher 사용법 (0) | 2022.07.18 |
---|---|
Android Studio - 에뮬레이터 한글 키보드 사용가능하게 세팅하기 (0) | 2022.07.15 |
Android Studio - RecycleView와 Adapter를 이용하여 리스트를 화면에 표시하는 방법 (0) | 2022.07.14 |
Android Studio - 빠르게 Linear Layout Resource 파일 만들기 (0) | 2022.07.14 |
Android Studio - ArrayList 에 저장된 데이터를 가져와 처리하는데 좋은 반복문 코드 (0) | 2022.07.14 |
댓글