Program Tip

Serializable을 사용하여 인 텐트를 통해 데이터 전달

programtip 2020. 11. 16. 22:03
반응형

Serializable을 사용하여 인 텐트를 통해 데이터 전달


직렬화 가능으로 클래스를 구현했지만 여전히 작동하지 않았습니다.

이것은 내 수업입니다.

package com.ursabyte.thumbnail;

import java.io.Serializable;

import android.graphics.Bitmap;

public class Thumbnail implements Serializable {

    private static final long serialVersionUID = 1L;
    private String label = "";
    private Bitmap bitmap;

    public Thumbnail(String label, Bitmap bitmap) {
        this.label = label;
        this.bitmap = bitmap;
    }

    public void set_label(String label) {
        this.label = label;
    }

    public String get_label() {
        return this.label;
    }

    public void set_bitmap(Bitmap bitmap) {
        this.bitmap = bitmap;
    }

    public Bitmap get_bitmap(){
        return this.bitmap;
    }

    //  @Override
    //  public int compareTo(Thumbnail other) {
    //      if(this.label != null)
    //          return this.label.compareTo(other.get_label());
    //      else
    //          throw new IllegalArgumentException();
    //  }

}

이것이 제가 전달하고 싶은 것입니다.

List<Thumbnail> all_thumbs = new ArrayList<Thumbnail>();
all_thumbs.add(new Thumbnail(string, bitmap));
Intent intent = new Intent(getApplicationContext(), SomeClass.class);
intent.putExtra("value", all_thumbs);

그러나 여전히 작동하지 않았습니다. Parcelable을 사용하는 방법을 모르기 때문에 대신 이것을 사용합니다.


Bundle.Serializable을 사용하여 직렬화 가능 목록을 전달하십시오 .

Bundle bundle = new Bundle();
bundle.putSerializable("value", all_thumbs);
intent.putExtras(bundle);

그리고 SomeClass Activity에서 다음과 같이 얻으십시오.

Intent intent = this.getIntent();
Bundle bundle = intent.getExtras();

List<Thumbnail> thumbs=
               (List<Thumbnail>)bundle.getSerializable("value");

이 코드는 다음과 같은 도움이 될 수 있습니다.

public class EN implements Serializable {
//... you don't need implement any methods when you implements Serializable
}

데이터 넣기. 추가로 새 활동 만들기 :

EN enumb = new EN();
Intent intent = new Intent(getActivity(), NewActivity.class);
intent.putExtra("en", enumb); //second param is Serializable
startActivity(intent);

새로운 활동에서 데이터 얻기 :

public class NewActivity extends Activity {

    private EN en;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        try {
            super.onCreate(savedInstanceState);

            Bundle extras = getIntent().getExtras();
            if (extras != null) {
                en = (EN)getIntent().getSerializableExtra("en"); //Obtaining data 
            }
//...

코드를 완전하고 실행 가능하게 만들기 위해 ρяσѕρєя K의 답변을 확장했습니다. 따라서 'all_thumbs'목록 작성을 마치면 콘텐츠를 하나씩 번들에 넣은 다음 인 텐트에 넣어야합니다.

Bundle bundle = new Bundle();

for (int i = 0; i<all_thumbs.size(); i++)
bundle.putSerializable("extras"+i, all_thumbs.get(i));

intent.putExtras(bundle);

인 텐트에서 추가 항목을 얻으려면 다음이 필요합니다.

Bundle bundle = new Bundle();
List<Thumbnail> thumbnailObjects = new ArrayList<Thumbnail>();

// collect your Thumbnail objects
for (String key : bundle.keySet()) {
thumbnailObjects.add((Thumbnail) bundle.getSerializable(key));
}

// for example, in order to get a value of the 3-rd object you need to:
String label = thumbnailObjects.get(2).get_label();

Advantage of Serializable is its simplicity. However, I would recommend you to consider using Parcelable method when you need transfer many data, because Parcelable is specifically designed for Android and it is more efficient than Serializable. You can create Parcelable class using:

  1. an online tool - parcelabler
  2. a plugin for Android Studion - Android Parcelable code generator

Sending Data:

First make your serializable data by implement Serializable to your data class

public class YourDataClass implements Serializable {
String someText="Some text";
}

Then put it into intent

YourDataClass yourDataClass=new YourDataClass();
Intent intent = new Intent(getApplicationContext(),ReceivingActivity.class);
intent.putExtra("value",yourDataClass);
startActivity(intent);

Receiving Data:

YourDataClass yourDataClass=(YourDataClass)getIntent().getSerializableExtra("value");

Intent intent = new Intent(getApplicationContext(),SomeClass.class);
intent.putExtra("value",all_thumbs);
startActivity(intent);

In SomeClass.java

Bundle b = getIntent().getExtras();
if(b != null)
thumbs = (List<Thumbnail>) b.getSerializable("value");

You need to create a Bundle and then use putSerializable:

List<Thumbnail> all_thumbs = new ArrayList<Thumbnail>();
all_thumbs.add(new Thumbnail(string,bitmap));
Intent intent = new Intent(getApplicationContext(),SomeClass.class);

Bundle extras = new Bundle();

extras.putSerializable("value",all_thumbs);
intent.putExtras(extras);

Create your custom object and implement Serializable. Next, you can use intent.putExtra("package.name.example", <your-serializable-object>).

In the second activity, you read it using getIntent().getSerializableExtra("package.name.example")

Otherwise, follow this and this page.


In kotlin: Object class implements Serializable:

class MyClass: Serializable {
//members
}

At the point where the object sending:

val fragment = UserDetailFragment()
val bundle = Bundle()
bundle.putSerializable("key", myObject)
fragment.arguments = bundle

At the fragment, where we want to get our object:

val bundle: Bundle? = arguments
    bundle?.let {
        val myObject = it.getSerializable("key") as MyClass
        myObject.memberName?.let { it1 -> showShortToast(it1) }
    }

Don't forget to implement Serializable in every class your object will use like a list of objects. Else your app will crash.

Example:

public class City implements Serializable {

private List<House> house;

public List<House> getHouse() {
    return house;
}

public void setHouse(List<House> house) {
    this.house = house;
}}

Then House needs to implements Serializable as so :

public class House implements Serializable {

private String name;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}}

Then you can use:

Bundle bundle = new Bundle();
bundle.putSerializable("city", city);
intent.putExtras(bundle);

And retreive it with:

Intent intent = this.getIntent();
Bundle bundle = intent.getExtras();
City city =  (City)bundle.getSerializable("city");

참고URL : https://stackoverflow.com/questions/14333449/passing-data-through-intent-using-serializable

반응형