Passing data through intent using Serializable
Asked Answered
B

13

80

I've implemented my class with serializable, but it still didn't work.

This is my class:

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();
    //  }

}

This is what I want to be passing.

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);

But still it didn't work. I don't know how to use Parcelable, so I use this instead.

Burford answered 15/1, 2013 at 8:6 Comment(4)
Bitmap class doesn't implement Serializable. You have to use Parcelable here. However, it's not a good idea to pass bitmaps using Parcelable...Kelpie
what about byte array? does it implement Serializable?Burford
yes, but be careful with large objects. Intent has a size limit for extrasKelpie
or you can add transient before bitmap like this private transient Bitmap bitmap;Hoshi
H
173

Try to pass the serializable list using Bundle.Serializable:

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

And in SomeClass Activity get it as:

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

List<Thumbnail> thumbs=
               (List<Thumbnail>)bundle.getSerializable("value");
Hoarsen answered 15/1, 2013 at 8:15 Comment(9)
I got this error : java.lang.RuntimeException: Parcelable encountered IOException writing serializable object (name = com.ursabyte.thumbnail.Thumbnail)Burford
@tegaralaga : see this example cnblogs.com/jsonxing/archive/2011/08/17/2143458.htmlTrypanosomiasis
The problem is Bitmap class doesn't implement Serializabe like @vmironov said :)Burford
@tegaralaga : yes i got it then Change Bitmap to image url and convert relevant image in next class instead of passing more bitmaps to other ActivityTrypanosomiasis
@tegaralaga : if this answer help in solving your current issue then mark it as answer.ThanksTrypanosomiasis
Actually I convert it into byte array. Thanks for your concern, mate :)Burford
As I understood the following line of your code needs to be changed to: bundle.putSerializable("value", all_thumbs.get(index));Cyperaceous
I had to declare as ArrayList<~>, didn't like just List<~>Ezechiel
@ρяσѕρєяK : How many Serializable Objects can we pass at one time through this bundle ?Yager
T
15

This code may help you:

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

Putting data. Create new Activity with extra:

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

Obtaining data from new activity:

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 
            }
//...
Terrorize answered 19/10, 2015 at 20:58 Comment(1)
The object "en" is comming nullableSkep
C
7

I extended ρяσѕρєя K's answer to make the code full and workable. So, when you finish filling your 'all_thumbs' list, you should put its content one by one into the bundle and then into the intent:

Bundle bundle = new Bundle();

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

intent.putExtras(bundle);

In order to get the extras from the intent, you need:

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
Cyperaceous answered 23/2, 2015 at 11:47 Comment(0)
P
7

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");
Prosenchyma answered 6/5, 2019 at 8:23 Comment(3)
This is only part of a solution to a well received question. Can you elaborate please?Galangal
Say you have un object House and you need to Serializable a class City that has a List of houses. You need to implement Serializable in the House class and the City ClassProsenchyma
Please improve your answer by including at least a few more words to help explain it. Use the edit button instead of adding a comment. Comments should be used for asking for more information or for suggesting improvements.Alible
H
6

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");
Heiney answered 19/7, 2018 at 6:9 Comment(0)
L
3
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");
Libelous answered 15/1, 2013 at 8:17 Comment(0)
D
3

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) }
    }
Dundalk answered 18/5, 2018 at 7:5 Comment(0)
P
2

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);
Polygynist answered 15/1, 2013 at 8:15 Comment(0)
H
1

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.

Heavy answered 15/1, 2013 at 8:17 Comment(0)
C
0

I use the following method when sending a List<MySerializableObject> via intent:

List<Thumbnail> thumbList = new ArrayList<>();
//Populate ...

Intent intent = new Intent(context, OtherClass.class);
intent.putExtra("ThumbArray", thumbList.toArray(new Thumbnail[0]));
//Send intent...

And retrieving it like so:

Thumbnail[] thumbArr = (Thumbnail[]) getIntent().getSerializableExtra("ThumbArray");
if (thumbArr != null) {
    List<Thumbnail> thumbList = Arrays.asList(thumbArr);
}
Chequer answered 9/3, 2020 at 9:42 Comment(0)
D
0

1- You are using android.graphics.Bitmap which doesn't implements Serializable class so you have to remove that class then it will work.

2- for brief you can visit how to pass data between intents.

Diphtheria answered 28/3, 2020 at 4:46 Comment(0)
C
0

If you're here because you did all of this and your app still crashes on switching activities:

My issues lied in my ParentClass using an object of another class in which I forgot to implement Serializable

public class A implements Serializable {
    
        private B[][] b;
    
}

public class B implements Serializable { //forgot this implementation

    B(){
    }

}
Cosmopolitan answered 18/11, 2021 at 17:34 Comment(0)
S
0

To pass a list, first implements Serializable in your class.

Then you must cast your list to serializable

val bundle = Bundle();
bundle.putSerializable("list", list as Serializable)

To get list in others activity or fragment

val intent = this.getIntent()
val bundle = intent.getExtras()
val thumbs: List<Thumbnail> = bundle.getSerializable("list") as List<Thumbnail>
Serve answered 17/3, 2022 at 7:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.