1

I am very new to Android development an m facing a little problem here. I have a class Animal. I need to pass an array of Animal class between two activities. I have searched the forums and found that this can be done with Parceable but I could not fully understand it. I tried using Serializable but got an Exception. Please guide me how this can be done?

0

3 Answers 3

7

Putting:

ArrayList<Animal> animals = new ArrayList<Animal>();
//fill your list with animals here

intent.putExtra("animals", animals);

Retrieving:

ArrayList<Animal> animals = (ArrayList<Animal>) getIntent()
                        .getSerializableExtra("animals");

Your class Animal should implement Serializable.

Edit: Please note, that this approach is easy-to-implement but is inefficient. It takes time to serialize and deserialize objects, and can cause noticeable delay in activities transition in case the array is large in size (say, 100+ objects, or 10+ complex, heavy objects). So please consider this approach as temporary and do not use it in production code.

For more efficiency, you can use Parcelable as suggested by David Caunt. Here's an easy-to-use code generator to avoid writing of boilerplate code by developer: Parcelabler.

A good alternative can be to have data stored in local SQLite DB upon obtaining and retrieveing from local DB in every Activity that needs it. Thus you will be passing only the Content Url via intent.

Sign up to request clarification or add additional context in comments.

Comments

2

You should implement Parcelable and then you can pass your object. You basically add a couple of methods to convert your object into a Parcel and vice-versa.

Parcelling is similar to Serialization but not the same. Think of it like rebuilding the object.

There's an example which does exactly what you're trying here.

Comments

0

Your class Animal should implement Serializable.

put data

   ArrayList<Animal> animals = new ArrayList<Animal>();

            Intent intent = new Intent(MainActivity.this,
                    AnimalListActivity.class);

            Bundle bundleObject = new Bundle();
            bundleObject.putSerializable("animal", animals);

            intent.putExtras(bundleObject);

            startActivity(intent);

get data

 ArrayList<Animal> animals = new ArrayList<Animal>();
 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.animal_activity);

    Bundle bundleObject = getIntent().getExtras();
    animals = (ArrayList<Animal>) bundleObject
            .getSerializable("animal");


    }
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.