반응형
다른 Activity로 class 객체 전달 방법
객체 전달할 클래스가 있는 Activity
package com.soej24.contackmanager.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;
}
}
전달할 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);
전달 받을 Activity
package com.soej24.contackmanager;
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.contackmanager.data.DatabaseHandler;
import com.soej24.contackmanager.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();
}
});
}
}
반응형
'TOOL > Android Studio' 카테고리의 다른 글
| Android Studio - ActionBar의 Title을 변경하는 방법 (0) | 2022.07.19 |
|---|---|
| Android Studio - SDK location not found Error (0) | 2022.07.15 |
| Android Studio - SharedPreferences를 이용한, 데이터 저장과 불러오기 (0) | 2022.07.13 |
| Android Studio - Activity간의 양방향 데이터 전달 방법 (0) | 2022.07.13 |
| Android Studio - Activity간의 단방향 데이터 전달 방법 (0) | 2022.07.13 |