Transfer data using Android intent vs. data objects in application class - android

I have to transfer objects between activities.
Objects are with complex structure.
I'm not sure what to do: to add bundle to intent or to store data in application class.
Which method is better /performance and garbage produced/?

The safest method is to bundle the data to pass with the Intent. This will be re-usable and avoid cluttering the global object space of the application. However this method is slightly more time consuming in that you have to implement Serializable for your custom types or create a custom Parcelable.

Related

Singleton vs Bundle to share/pass object from one activity to another

I want to share object from one activity to another activity. I know of 2 good ways:
Using bundle: By making object's class implement Parcelable, can pass object in bundle via intent.
Using singleton pattern: saving the object instance in this class and then fetch it where ever required.
Which of the above mentioned is better or recommended way? Kindly also tell if there is some other better way.
Singleton isn't a good ideia on Activities, because it will produce memory leak (redundancy of information of an Activity).
Parcelable it's a good idea, because you will not use disk IO or Network when you create a local object from a form in the first Activity.
If you retrieve an object from Network or local database, you don't need anyone, because you can retrieve the object in the next Activity.

What's the point of bundles in Android?

If I pass a bundle to an activity from MyActivity to MyFragment using setArgs and getArgs. Couldn't I have just passed the data objects through the MyFragment constructor? What's the point of all this bundle stuff? Is it faster?
Side question: When I pass bundles around, are they aliased? So that editing the bundle will change everything?
The bundle is needed to manage the lifecycle of the fragment and to allow the OS to create again the object. Other info here docs
Well, I think this needs some introducing:
If an Activity or Fragment will be f.e. destroyed the state of them will be saved. Therefor this state must be saved by the system to be able to recreate it. The best thing to do is to save it as a byte code with all information necessary to rebuild the objects which define this state. With the use of byte code it doesn't matter of which type this objects are. The transformation of objects into byte code is called serialization.
Android has it's own serialization mechanism called Parcelable. It's much faster than the serialization Java provides by default and because of this it should be the prefered way to use in Android.
Now Bundles only take Objects, which implements the Parcelable or the Serializable interface, and primitives. They are used to save the different objects which define the state of Activities/Fragments at one place.
Because the arguments which you can pass to a Fragment will also be serialized by the system for future use, a Bundle is needed. This is the reason why a Fragment should only use a non-arg constructor and pass the parameters through the arguments.
In short: A Bundle is used by the system to save and recreate the state of Activities or Fragments. Therefor the system uses a format for this data which is easily readable, a byte code.
the big deal in budnles is that they work between applications. This makes for the possibility to run, for example, the browser, with a website that is programmed in the app. If you would start the browser whilst passing data through a constructor, the browser window would run in the same thread as the application that you started running it through. Bundles and intents make the operating system more secure.

How to pass a just created object from one activity to another?

My app contains 2 activitys. Activity A is the one which is created by starting the app. In this one I create an object of my own class MyClass. This class contains one string and 3 integers. In activity A this object gets written.
The second activity B needs to read this object. How can I pass it from A to B? Or is there an other solution?
There are couple of way you can pass an object from one activity to another:
1. Application Class: this class is visible to all your application Activities so you can save your object in this class from one Activity and then access it from the other.
2. You can break apart your Class into the simple variables: string and 3 integers and pass them via a bundle or the intent it self from one activity to another, then construct your object again.
Intent intent = new Intent (this, TargetActivity.class);
intent.putExtra(KEY, value);
intent.putExtra(KEY, "value");
startActivity(intent);
3. If your object implements Serializable/Parcelable then you can pass it via a bundle.
Example on how to serialize an object:
How do I serialize an object and save it to a file in Android?
One option could be implementing Serializable interface and then you can pass object instances in intent extra using putExtra(Serializable..) variant of the Intent#putExtra() method.
//to pass :
intent.putExtra("MyClass", obj);
// to retrieve object in second Activity
getIntent().getSerializableExtra("MyClass");
It can be tricky, because there's no guarantee that your application can't be killed between activities. Actually, it can be killed during activities, so keeping persistent objects around can be tricky.
My preferred way to do this is the "singleton pattern" in which you create a class whose purpose is to create a single instance that holds whatever data you want to hang around. If your application gets killed, the singleton instance will be lost and have to be re-created, but all Android apps run this risk all the time anyway.
See Save multiple instances states of the same Activity in Android for my implementation of a singleton in Android.
Oh, and I should add that this only works within an application where all the activities are in the same process, sharing the same address space. Otherwise, you'll have to make your object serialiazable and write it off to a file.

Working with same data in three activities

I'm not very experienced in android specific components, so I just can't get where I need to look.
I have three activities:
1st gets info about some groups of objects, user selects some of this groups and activity needs to star next activity
2nd activity shows all objects from groups, that user selected at previous activity, here user can deselect some selected objects and then activity starts 3d activity
3d activity allows user to do something with selected objects
My solution is make some singleton model, that let activities get and save information about objects,
but i suppose, that android has some special components to provide data between activities
Help me to find this components^ please
It depends on the type of data that you want to share:
Primitive Data Types
To share primitive data between Activities/Services in an application, use Intent.putExtras(). For passing primitive data that needs to persist use the Preferences storage mechanism.
Non-Persistent Objects
For sharing complex non-persistent user-defined objects for short duration, the following approaches are recommended:
The android.app.Application class
The android.app.Application is a base class for those who need to maintain global application state. It can be accessed via getApplication() from any Activity or Service. It has a couple of life-cycle methods and will be instantiated by Android automatically if your register it in AndroidManifest.xml.
A public static field/method
An alternate way to make data accessible across Activities/Services is to use public static fields and/or methods. You can access these static fields from any other class in your application. To share an object, the activity which creates your object sets a static field to point to this object and any other activity that wants to use this object just accesses this static field.
A HashMap of WeakReferences to Objects
You can also use a HashMap of WeakReferences to Objects with Long keys. When an activity wants to pass an object to another activity, it simply puts the object in the map and sends the key (which is a unique Long based on a counter or time stamp) to the recipient activity via intent extras. The recipient activity retrieves the object using this key.
A Singleton class
There are advantages to using a static Singleton, such as you can refer to them without casting getApplication() to an application-specific class, or going to the trouble of hanging an interface on all your Application subclasses so that your various modules can refer to that interface instead.
But, the life cycle of a static is not well under your control; so to abide by the life-cycle model, the application class should initiate and tear down these static objects in the onCreate() and onTerminate() methods of the Application Class
Persistent Objects
Even while an application appears to continue running, the system may choose to kill its process and restart it later. If you have data that you need to persist from one activity invocation to the next, you need to represent that data as state that gets saved by an activity when it is informed that it might go away.
For sharing complex persistent user-defined objects, the following approaches are recommended:
Application Preferences
Files
contentProviders
SQLite DB
If the shared data needs to be retained across points where the application process can be killed, then place that data in persistent storage like Application Preferences, SQLite DB, Files or ContentProviders.
yes, you can send data between activities using Intents. Using the putExtra() function for that. If you want to pass your own objects, you need to implement Parcalable class.
There is no problem with using a singleton to share information between your Activities, especially if you need this data to be consistent throughout your whole app.
Alternatively you could use an Intent to pass data between Activities - putExtra().
Yes it does:
http://www.remwebdevelopment.com/dev/a33/Passing-Bundles-Around-Activities.html
Basically you can either send a Bundle or just use putExtra function for that.
try this way please
Intent i = new Intent(this, YourTragetedActivity.class);
i.putExtra("value1", "test1");
i.putExtra("value2", "test2");
startActivity(i);
//// On Your TragetedActivity
getIntent().getStringExtra("value1")
getIntent().getStringExtra("value2")

Android: Send arbitrary objects within Activities?

I have read some question here but I didn't find a solution. I have read about Parcelable, Intents, and sharing specific data within Activities from the android dev docs (both dev guide and reference).
Here's the scenario:
I have one ListActivity that fills in an object parsing an xml file, it shows a list of values, and when clicked I want to return the object that represents the item clicked to the activity that has called it, for then, call another activity with this object.
I read on how to implement Parcelable but seems not being the way. Implementing Parcelable receives a Parcel for the constructor and then reads the values from it (or at least that was what I understood). This makes no sense for me and I can't see how to implement basing on that issue. I build the object parsing the xml file, not having a Parcel.
I appreciate some clarifications on this, regards.
I believe you have three options here:
Pass some arbitrary 'id' of the object to the new activity in the intent extras, which obtains the object in the same way as the first activity. This I would recommend as it is in harmony with the way Android is designed to work.
Serialize the object using Java Serializable, then put it into the intent as an extra.
Have the object be a JSONObject and send it as a string in the intent extras.
That depends on whether the activities belong to the same process or different ones...if it is the same process then the answer is Within an application what is the best way to pass custom objects between activities? but if they belong to different processes then you are better of implementing parcelable.

Categories

Resources