Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing data of a non-primitive type between activities in android

Tags:

Suppose you want to start a new activity and pass it some data from the current activity. If the data is of a primitive type you could simply use an intent and add extras, but how would you do this for more complex data structures like arraylists or objects?

like image 455
aspartame Avatar asked Sep 17 '09 23:09

aspartame


People also ask

Can we pass non-primitive data types from one activity to another activity?

You have a few options: You could wrap the more complex structure in a class that implements the Parcelable interface, which can be stored in an extra. You could wrap the more complex structure in a class that implements the Serializable interface, which can be stored in an extra.

What way is used to pass between activities in android?

We can send the data using putExtra() method from one activity and get the data from the second activity using the getStringExtra() method.

How are non-primitive types passed in Java?

Non-primitive types are created by the programmer and is not defined by Java (except for String ). Non-primitive types can be used to call methods to perform certain operations, while primitive types cannot. A primitive type has always a value, while non-primitive types can be null .

What is the difference between passing primitive data types versus passing objects?

When you pass a primitive, you actually pass a copy of value of that variable. This means changes done in the called method will not reflect in original variable. When you pass an object you don't pass a copy, you pass a copy of 'handle' of that object by which you can access it and can change it.


1 Answers

You have a few options:

  1. You could wrap the more complex structure in a class that implements the Parcelable interface, which can be stored in an extra
  2. You could wrap the more complex structure in a class that implements the Serializable interface, which can be stored in an extra
  3. You use static data members to pass stuff around, since they are all in the same process
  4. You use external storage (file, database, SharedPreferences)
  5. As the person who just posted noted, use a common component, such as a custom Application or a local Service

What you do not want to do is pass big stuff via extras. For example, if you are creating an application that grabs pictures off the camera, you do not want to pass those in extras -- use a static data member (icky as that sounds). Intents are designed to work cross-process, which means there is some amount of data copying that goes on, which you want to avoid when it is not necessary for big stuff.

like image 80
CommonsWare Avatar answered Oct 20 '22 00:10

CommonsWare