티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
How to pass an object from one activity to another on Android
Android에서 한 액티비티에서 다른 액티비티로 객체를 전달하는 방법
문제 내용
I am trying to work on sending an object of my customer class from one Activity
and displaying it in another Activity
.
한 액티비티에서 고객 클래스의 객체를 전송하여 다른 액티비티에 표시하려고 합니다.
The code for the customer class:
고객 클래스의 코드:
public class Customer {
private String firstName, lastName, address;
int age;
public Customer(String fname, String lname, int age, String address) {
firstName = fname;
lastName = lname;
age = age;
address = address;
}
public String printValues() {
String data = null;
data = "First Name :" + firstName + " Last Name :" + lastName
+ " Age : " + age + " Address : " + address;
return data;
}
}
I want to send its object from one Activity
to another and then display the data on the other Activity
.
한 액티비티에서 다른 액티비티로 객체를 보낸 다음 다른 액티비티에 데이터를 표시합니다.
How can I achieve that?
어떻게 하면 그것을 이룰 수 있을까요?
높은 점수를 받은 Solution
One option could be letting your custom class implement the Serializable
interface and then you can pass object instances in the intent extra using the putExtra(Serializable..)
variant of the Intent#putExtra()
method.
한 가지 옵션은 사용자 정의 클래스가 Serializable 인터페이스를 구현하도록 한 다음 Intent#putExtra() 메서드의 putExtra(Serializable..) 사용하여 인텐트 Extra에 객체 인스턴스를 넣어 전달할 수 있습니다.
Actual Code:
실제 코드:
In Your Custom Model/Object Class:
사용자 지정 모델/객체 클래스:
public class YourClass implements Serializable {
At other class where using the Custom Model/Class:
사용자 정의 모델/클래스를 사용하는 다른 클래스:
//To pass:
intent.putExtra("KEY_NAME", myObject);
myObject is of type "YourClass". Then to retrieve from another activity, use getSerializableExtra get the object using same Key name. And typecast to YourClass is needed:
myObject는 "YourClass" 타입입니다. 그런 다음 다른 액티비티에서 검색하려면 getSerializableExtra를 사용하여 동일한 키 이름을 사용하여 객체를 가져옵니다. 그리고 YourClass로의 typecast가 필요합니다.
// To retrieve object in second Activity
myObject = (YourClass) getIntent().getSerializableExtra("KEY_NAME");
Note: Make sure each nested class of your main custom class has implemented Serializable interface to avoid any serialization exceptions. For example:
참고: 직렬화 예외를 방지하려면 주 사용자 지정 클래스의 각 중첩 클래스에 직렬화 가능한 인터페이스가 구현되어 있는지 확인하십시오.
예:
class MainClass implements Serializable {
public MainClass() {}
public static class ChildClass implements Serializable {
public ChildClass() {}
}
}
가장 최근 달린 Solution
Start another activity from this activity and pass parameters via Bundle Object
이 액티비티에서 다른 액티비티를 시작하고 번들 개체를 통해 매개 변수 전달
Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("USER_NAME", "xyz@gmail.com");
startActivity(intent);
Retrieve data on another activity (YourActivity)
다른 액티비티(YourActivity)에 대한 데이터 검색
String s = getIntent().getStringExtra("USER_NAME");
This is ok for a simple kind of data type. But if u want to pass complex data in between activities. U need to serialize it first.
이것은 단순한 종류의 데이터 유형에 적합합니다. 그러나 액티비티 사이에 복잡한 데이터를 전달하려는 경우. 먼저 직렬화해야 합니다.
Here we have Employee Model
여기 Employee 모델이 있습니다.
class Employee{
private String empId;
private int age;
print Double salary;
getters...
setters...
}
You can use Gson lib provided by google to serialize the complex data like this
구글이 제공하는 Gson lib을 사용하여 복잡한 데이터를 이것처럼 직렬화할 수 있습니다.
String strEmp = new Gson().toJson(emp);
Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("EMP", strEmp);
startActivity(intent);
Bundle bundle = getIntent().getExtras();
String empStr = bundle.getString("EMP");
Gson gson = new Gson();
Type type = new TypeToken<Employee>() {
}.getType();
Employee selectedEmp = gson.fromJson(empStr, type);
출처 : https://stackoverflow.com/questions/2736389/how-to-pass-an-object-from-one-activity-to-another-on-android
'개발 > 안드로이드' 카테고리의 다른 글
웹뷰에서 html 콘텐츠 가져오기 (0) | 2022.12.17 |
---|---|
당겨서 새로고침 구현하기 (0) | 2022.12.17 |
Cause: Already disposed: Module: 'MYMODULENAME' 문제 수정하기 (0) | 2022.12.17 |
액티비티 타이틀 바 숨기는 방법 (0) | 2022.12.16 |
'Error type 3 Error: Activity class {} does not exist' 오류 수정하기 (0) | 2022.12.16 |