메뉴 건너뛰기

?

단축키

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 객체의 멤버 변수 값들을 지정해줍니다.

 

 

 


  1. 안드로이드 - RecyclerView 안에 RecyclerView 구현하기

  2. 안드로이드 - Json 파싱하기

  3. No Image 01Apr
    by
    2021/04/01 Views 1365 

    안드로이드 - 타이머(Timer) 구현하기

  4. 안드로이드 - SQLiteDatabase 구현하기

  5. 안드로이드 - 리사이클러 뷰(RecyclerView) 구현

  6. 안드로이드 - 네비게이션 드로어(Navigation Drawer)를 활용하여 슬라이드 메뉴 구현하기

  7. 안드로이드 - 툴바(ToolBar)를 사용하여 앱바(App Bar) 구현하기

  8. 안드로이드 - 프로그레스바(ProgressBar) 구현하기

  9. 안드로이드 - AsyncTask 구현 예제

  10. 안드로이드 - 액티비티(Activity)와 액티비티 생명 주기(Activity Life Cycle)

  11. 안드로이드 - 리스트뷰(ListView) 구현

  12. 안드로이드 - 컨텍스트 메뉴(Context Menu) 사용 예제

  13. 안드로이드 - 옵션 메뉴 (Option Menu) 구현 방법

  14. 안드로이드 - 명시적 인텐트(Explicit Intent)와 암시적 인텐트 (Implicit Intent)

  15. 안드로이드 - 날짜 및 시간 정보 입력받기 (DatePickerDialog / TimePickerDialog)

  16. No Image 01Apr
    by
    2021/04/01 Views 227 

    안드로이드 - setContentView()와 레이아웃 전개자(LayoutInflater)

  17. 안드로이드 - AlertDialog 사용하여 알림창 띄우는 방법 총정리

  18. 안드로이드 - SnackBar를 사용해 팝업창 띄우기

  19. 안드로이드 - 토스트(Toast) 메시지 사용하기.

  20. 안드로이드 - 액티비티(Activity)로부터 결과 데이터 받아오기

Board Pagination Prev 1 2 3 4 5 6 7 8 9 10 ... 13 Next
/ 13

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

© k2s0o1d4e0s2i1g5n. All Rights Reserved