메뉴 건너뛰기

?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄 첨부
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄 첨부
public class Person{
    private String name;
    private int age;

    public void setName(String name)
    {
        this.name = name;
    }

    public void setAge(int age)
    {
        this.age = age;
    }

    public String getName()
    {
        return this.name;
    }

    public int getAge()
    {
        return this.age;
    }
}

▼ Person 클래스는 멤버 변수 2개와 각 멤버 변수에 접근할 수 있는 멤버 함수 getter/setter가 정의되어 있는 클래스입니다. Person 클래스 안에 멤버 변수들은 연속된 메모리에 할당되지 않기 때문에 직렬화 객체가 될 수 없습니다. 우리가 다른 액티비티에 이러한 데이터 객체를 넘겨주기 위해서는 값이 변경될 수 있는 멤버 변수들을 연속된 메모리에 할당된 형태인 직렬화 형태로 변경해야 가능합니다.


1. 직렬화 객체 생성하기

위에서 살펴본 Person 클래스의 객체를 직렬화 시키기 위해서는 Serializable 인터페이스를 구현해야 합니다. 

public class Person implements Serializable{

    private static final long serialVersionUID = 1L;
    private String name;
    private int age;

    public void setName(String name)
    {
        this.name = name;
    }

    public void setAge(int age)
    {
        this.age = age;
    }

    public String getName()
    {
        return this.name;
    }

    public int getAge()
    {
        return this.age;
    }
}

▼ Serializable 인터페이스를 상속받았지만 따로 오버 라이딩하는 함수는 보이지 않습니다. 

그 이유는 Serializable 인터페이스는 마커 인터페이스(Marker Interface)로 단순히 시스템에 내부의 멤버 변수들을 직렬화하여 객체를 생성해야 한다고 알리는 용도입니다. 다만 멤버 변수로 serialVersionUID라는 멤버 변수가 추가된 것을 확인할 수 있습니다. 해당 값은 직렬화된 클래스의 버전을 의미합니다. 즉, 객체를 전달하는 측과 해당 객체를 수신하는 측에서 사용하는 클래스 파일이 동일한지 체크하는 용도로 사용됩니다. 

 

2. 객체 전달하기

객체를 전달할 때도 일반적인 데이터 타입의 변수를 전달할 때와 마찬가지로 인텐트(Intent)를 활용합니다. 

 

 

 

▼ 앞서 구현했던 Person 객체를 MainActivity에서 생성하여 SubActivity에 전달하는 예제를 구현할 것입니다. 

먼저 MainActivity 화면 UI를 위한 XML 레이아웃 리소스입니다. 

    <LinearLayout
        android:id="@+id/layout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="8dp">

        <Button
            android:id="@+id/button2"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:onClick="OnClickHandler"
            android:text="Sub Activity 실행하기" />
    </LinearLayout>

▼ 최상위 LinearLayout 아래에 Button 하나가 배치된 단순한 형태입니다. 해당 버튼을 클릭하면 SubActivity를 실행하는 형태입니다.

public class MainActivity extends AppCompatActivity{
    private Person person;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        this.InitializeData();
    }

    public void InitializeData()
    {
        person = new Person();
        person.setName("LKT Programmer");
        person.setAge(1234);
    }

    public void OnClickHandler(View view)
    {
        Intent intent = new Intent(this,SubActivity.class);

        intent.putExtra("person", person);

        startActivity(intent);
    }
}

▼ InitializeData() 함수에서 Person 객체를 생성합니다. 각 멤버 변수의 setter 함수를 통해 멤버변수의 값을 지정해주고 있습니다. 

 

 

▼ OnClickHandler() 함수는 버튼 클릭에 대한 이벤트 처리를 담당하는 함수입니다.

 

putExtra() 함수를 통해 person 객체를 Intent에 담고 있습니다. 그런 다음 startActivity() 함수를 호출하여 Sub 액티비티를 실행합니다. 


3. 객체 수신하기

이번에는 MainActivity에서 전달한 Person 객체를 SubActivity에서 수신하는 부분입니다. 먼저 Sub Activity의 화면 UI를 구성하는 XML 레이아웃 리소스입니다.

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:id="@+id/person"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="TextView" />
    </LinearLayout>

▼ 최상위 LinearLayout 아래에 TextView가 배치된 형태입니다. TextView는 전달된 Person 객체의 멤버 변수 값을 표시하기 위한 용도로 사용합니다.

public class SubActivity extends AppCompatActivity {

    private TextView textView_person;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sub);

        Intent intent = getIntent();

        Person person = (Person)intent.getSerializableExtra("person");

        textView_person = (TextView)findViewById(R.id.person);

        textView_person.setText("이름 :" + person.getName() + "/ 나이 : " + person.getAge());
    }
}

▼ 먼저 MainActivity에서 전달한 Intent 객체를 수신하기 위해 getIntent() 함수를 통해 참조 객체를 얻어옵니다. 다음으로 Intent 클래스에서 제공하는 getSerializableExtra() 함수를 통해 MainActivity에서 전달한 Person 객체를 얻어옵니다. 그런 다음 TextView 참조 객체를 얻어와 setText를 통해 Person 객체의 멤버 변수 값들을 지정해줍니다.

 

 

 


List of Articles
번호 제목 날짜 조회 수
137 안드로이드 종료 취소 다이얼로그 코드 2015.07.26 6389
136 체크 박스(CheckBox)의 이미지 바꾸기 2015.07.16 6398
135 jQuery Ajax - jQuery.load() 메서드 (동적으로 원격 페이지 로드) file 2014.10.16 6417
134 HTML5로 나만의 비디오 플레이어 스킨 만들기 -1- CSS file 2014.09.04 6453
133 HTML5 Speech Input (음성인식) API 2014.09.04 6454
132 맵에 오버레이 추가하여 아이템 넣어보기 2014.08.28 6474
131 Android] Fragment 내부의adapter에서 startActivity 하기 2015.12.15 6487
130 폰갭 비콘 디텍팅 안될 때 (기본적인건 다 되있어야됨) 2015.07.26 6529
129 ScrollView의 활용 2015.07.16 6530
128 서비스가 실행중인지 알아보는 방법 2015.07.16 6553
127 JSON(JavaScript Object Notation) - jQuery Ajax - jQuery.getJSON() 메서드 (비동기적으로 JSON파일 로드) file 2014.10.16 6568
126 JavaScript 맛보기 file 2014.09.04 6589
125 실행중인 Service 확인하기 2014.08.28 6595
124 버튼 누르면 이미지 바꾸기 file 2015.07.26 6613
123 Android TIP] strings.xml 에서 특수문자 사용하기 2015.12.15 6629
122 안드로이트 비콘 스캐닝시 고려 사항 2015.07.26 6658
121 안드로이드 스튜디오 gradle error 해결 2015.07.23 6683
120 jQuery ajax post 요청 text 응답 2014.10.16 6702
119 트리뷰(TreeView) 컨트롤 file 2014.10.16 6722
118 푸쉬 알림 기능. GCM (Google Cloud Messaging) 사용하기 (1) file 2015.07.16 6726
Board Pagination Prev 1 2 3 4 5 6 7 8 9 10 11 ... 13 Next
/ 13

하단 정보를 입력할 수 있습니다

© k2s0o1d4e0s2i1g5n. All Rights Reserved