使用可序列化通过意图传递数据

2022-08-31 12:57:19

我已经使用可序列化实现了我的类,但它仍然不起作用。

这是我的类:

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,所以我用这个代替。


答案 1

尝试使用 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");

答案 2

此代码可以帮助您:

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 
            }
//...

推荐