Solve Problem/Android
[Android] Activity 전환 시 객체 전달하기! : Parcelable, Serializable
안다희
2019. 1. 6. 23:11
728x90
TagNames라는 클래스가 있다.
package org.techtown.just; import java.io.Serializable; public class TagNames implements Serializable { private String[] tags = {"행복", "슬픔", "힐링"}; private int[] tagIndex; public String[] getTags() { return tags; } public int[] getTagIndex() { return tagIndex; } public void setTagIndex(int i) { tagIndex[i] = 1; } public TagNames() { tagIndex = new int[tags.length]; for (int i = 0; i < tags.length; i++) tagIndex[i] = 0; } } |
Activity를 전환할 때 이 tagNmaes 객체를 전달하고 싶으면
1. TagNames class는 Serializable을 implements 한다. (위에 빨간 글씨)
2.
Intent intent = new Intent(this, RecommendDetailActivity.class); intent.putExtra("tagNames", tagNames); startActivity(intent); |
위처럼 intent.putExtra(전달name, 전달할 객체); 를 써준다.
3. 이 intent를 받는 액티비티에서는
Intent intent = getIntent(); TagNames tagNames = (TagNames) intent.getSerializableExtra("tagNames"); |
이렇게 intent.getSerializableExtra(전달name); 으로 받는다.
** 형변환은 필수! (TagNames) 처럼!! 안그럼 빨간줄 생김
123단계만 잘 따라하면 extra로 객체도 전달하기 성공!
참고링크