본문 바로가기
Back End/Android(

Android/ 다른 액티비티(Activity)로 데이터 전달시 클래스(class)의 객체 전달 방법

by healingmau 2022. 7. 15.

 

다른 액티비티(Activity)로 데이터 전달시 클래스(class)의 객체 전달 방법

 

1.

Serializable 직렬화

저장하거나 네트워크 전송을 하기 위해서

객체를 텍스트나 이진 형식으로

변환하는 것을 말합니다.

 

클래스에서 Serializable

인터페이스를 상속받아 구현!

 

액티비티(Activity)에 보낼때

intent.putExtra()로 보내고,

받는 액티비티에서

getSerializableExtra()로 

받을수 있습니다.

 

//보낼때:
intent.putExtra("MyClass", obj);

// 액티비티에서 받을때
getIntent().getSerializableExtra("MyClass");

 

a.

model/Contact.java

(객체 전달한 클래스가 있는 파일)

 

package com.soej24.contactmanager.model;

import java.io.Serializable;

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

    public Contact(int id, String name, String phone) {
        this.id = id;
        this.name = name;
        this.phone = phone;
    }

    public Contact(String name, String phone) {
        this.name = name;
        this.phone = phone;
    }
}

 

b.

전달할 액티비티(Activity)

 

// 데이터를 클래스 전체 데이터로 보내는 방법
// 보낼 클래스로 이동해서 implements Serializable 기재한다.
intent.putExtra("contact", contact);

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

 

c.

EditActivity.java

(전달받을 액티비티가 있는 파일)

 

package com.soej24.contactmanager;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.soej24.contactmanager.data.DatabaseHandler;
import com.soej24.contactmanager.model.Contact;

public class EditActivity extends AppCompatActivity {

    // 넘어온 데이터에 대한 멤버변수
    int id;
    String name;
    String phone;

    Contact contact;

    // 화면 UI 에 대한 멤버변수
    EditText editName;
    EditText editPhone;
    Button btnSave;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit);
        
        // 다른액티비티로부터 넘겨받은 데이터가 있으면, 이 데이터를 먼저 처리하자.

        contact = (Contact) getIntent().getSerializableExtra("contact");

//        id = getIntent().getIntExtra("id", 0);
//        name = getIntent().getStringExtra("name");
//        phone = getIntent().getStringExtra("phone");
        
        // 화면과 변수 연결
        editName = findViewById(R.id.editName);
        editPhone = findViewById(R.id.editPhone);
        btnSave = findViewById(R.id.btnSave);

        // 넘겨받은 데이터를 화면에 셋팅!!!!!
        editName.setText(contact.name);
        editPhone.setText(contact.phone);

        // 버튼 클릭시 처리할 코드 작성 : DB 에 저장하고, 액티비티 종료해서, 메인으로돌아감.
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String name = editName.getText().toString().trim();
                String phone = editPhone.getText().toString().trim();

                if(name.isEmpty() || phone.isEmpty()){
                    Toast.makeText(EditActivity.this, "이름이나 전화번호는 필수입니다.", Toast.LENGTH_SHORT).show();
                    return;
                }

                DatabaseHandler db = new DatabaseHandler(EditActivity.this);

                // 업데이트에 필요한 파라미터는, Contact  클래스의 객체다.
                // 따라서 Contact 클래스의 객체를 만들어서, 함수호출해준다.
//                Contact contact = new Contact(id, name, phone);

                contact.name = name;
                contact.phone = phone;

                db.updateContact(contact);

                // 액티비종료하면, 자동으로 메인액티비티가 나온다.
                finish();
            }
        });
    }
}

 

힐링아무의 코딩일기 힐코딩!!

댓글