군침이 싹 도는 코딩

다른 액티비티로 데이터 전달 시 클래스의 객체를 전달하는 방법 ( Serializable, putExtra() , getSerializableExtra() ) 본문

Android

다른 액티비티로 데이터 전달 시 클래스의 객체를 전달하는 방법 ( Serializable, putExtra() , getSerializableExtra() )

mugoori 2023. 2. 1. 17:49
package com.mugoori.contactapp.model;

import java.io.Serializable;
// 클래스를 직렬화 함
public class Contact implements Serializable {

    public int id;
    public String name;
    public String phone;


    public  Contact(){

    }

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

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

# 다른 액티비티로 데이터를 전달시에 쓰는 intent를 통해 데이터를 하나씩 전달해도 되지만

그렇게하면 유지보수를할때 한줄한줄 다시 추가를 해야하는 불편함이있다

따라서 객체를 통째로 전달하는것이 편리하다 먼저 객체생성할 클래스를 직렬화한다

클래스의 이름 옆에 implements Serializable을 써준다

이렇게하면 클래스가 직렬화된다

 

 

 

 

 

public class viewHolder extends RecyclerView.ViewHolder{

        TextView txtName;
        TextView txtPhone;
        ImageView imgDelete;
        CardView cardView;

        public viewHolder(@NonNull View itemView) {
            super(itemView);
            txtName = itemView.findViewById(R.id.txtName);
            txtPhone = itemView.findViewById(R.id.txtPhone);
            imgDelete = itemView.findViewById(R.id.imgDelete);
            cardView = itemView.findViewById(R.id.cardView);

            cardView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // 1. 인텐트에 유저가 누른 이름과 전화번호를 담는다
                    int index = getAdapterPosition();

                    Contact contact = contactList.get(index);

                    // 2. 수정 액티비티를 띄운다
                    // 어떤 액티비티가 어떤 액티비티를 띄운다
                    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);

                }
            });
        }
    }

# 직렬화한 클래스를 인텐트 객체 생성할 때 파라미터로 넣어주고 실행할 클래스를 써준다

putExtra 로 전달해줄 클래스 객체의 키값과 데이터를 써준다

 

 

 

 

package com.mugoori.contactapp;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;

import com.mugoori.contactapp.model.Contact;

public class EditActivity extends AppCompatActivity {

    EditText editName;
    EditText editPhone;
    Button btnSave;

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

        editName = findViewById(R.id.editName);
        editPhone = findViewById(R.id.editPhone);
        btnSave = findViewById(R.id.btnSave);

//        int id = getIntent().getIntExtra("id",0);
//        String name = getIntent().getStringExtra("name");
//        String phone = getIntent().getStringExtra("phone");
//        editName.setText(name);
//        editPhone.setText(phone);

        // 일렬로 만든것을 다시 원상복구해서 가져온다 ( Contact )
        Contact contact = (Contact) getIntent().getSerializableExtra("contact");

        editName.setText(contact.name);
        editPhone.setText(contact.phone);




    }
}

# getIntent.getSerializableExtra 를 써주고 파라미터로 키값을 넣어준다

그러면 오류가 발생하는데 이것은 일렬로 만든것을 다시 Contact의 형태로 복구해줘야 한다

복구를 해준다음 변수에 저장한다

마지막으로 받아온 데이터를 원하는곳에 세팅해주면 된다