Android: Send arbitrary objects within Activities? - android

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.

Related

android globally object reference for all activities

May be its simple question, may be its repeated question, this question s not for upvote and all.
I just want to pass my object from one activity to second and second to third activity. I know there are a lot of ways using shared preferences, Intent bundle from one to another activity.
The reason I want to know that why I can't use an object globally for all my activities and if I can how it is possible?
Thanks
There is a handful of ways in which you can achieve this.
Using a bus/listener:
https://github.com/greenrobot/EventBus
https://square.github.io/otto/
Using the application class (ready the first answer carefully, there are caveats):
How to declare global variables in Android?
And using utility classes with static methods.
Also, if you are have more than one fragment running at the same time, you can create your own interfaces and implement them where you need to receive the information.

Better way to retain/pass data between activities

I am making an Android app using the Parse SDK. What I am struggling with is the flow of creating a post. Currently, in my main activity, a user selects the type of post (photo, video, etc.) takes a photo/video and goes to the next activity called NewActivity. In this activity, a user can review the photo/video and edit the privacy or place of the post. to change the privacy or place launches a new activity for each.
The main problem I'm having is retaining and passing this Post object between the activities.
My first (bad) solution was just to pass the data with the intent in a Bundle, but this soon got very messy as I really needed to pass a Post object between the activities. I switched from that solution to using a Singleton class called, DataHolder.
In each activity, I call DataHolder.getInstance() and when the create post button is clicked, I create a new Post object by executing: DataHolder.getInstance().setPost(new Post()). In the following activities, as the user enters more information about a post, I set the Post's properties.
This was all working well until I ran into this issue. When I would return to my app (presumably it had been killed) I would get a NullPointerException because the Post object was null. I was looking through the Android docs on passing data between activites/services and needed a little help.
Should I be using the Singleton class pattern here? What would be the most efficient and easiest way to pass this Post object between the activities? Should I use an application singleton? I would use Parcelable or Serializable, but the Postobject is a ParseObject so this is not an option. Should I avoid passing the data altogether by using Fragments for the privacy and place activities (though they have different screens and different action bars)? Should I use startActivityForResult for the privacy and place activities?
You should consider that the app could be killed at any moment for any reason and be prepared for this. You could use something like a session object to communicate between activities. You can save it / load it as often as needed so you will not run the risk of loosing data. If you cannot serialize the actual object (eg the ParseObject) you could serialize the parts needed in order to reconstruct it (ie save the image in a temp folder and load it on demand).

Which is better: Parcelable or Context?

I'm on the situation where I have to share variables between activities... but I have one doubt. Which is better: Parcelable object or set it on a custom Application object.
When something is just going to be used in next activity I just pass it as a Parcelable object, and when it is going to be used in more than one activity, I put it on Application context.
What do you think? Is it right? Which is better in performance?
Thanks!
I think your approach is completely valid.
If it is something like a user object that is accessed in every Activity store it in a custom Application object, but be sure to have a way to recreate the object if the application object gets destroyed while the app is in background.
If it is something like a path or a choice the user made that determines how the next activity works send it with the Intent.
There are also some classes that are not easy to put in an Intent. I have an ImageCache that is attached to the application class that allows to keep images like a user profil image in memory between activity changes without the need to decode the bitmap multiple times. If they are designed in a way that they don't fill up all available memory those are also a good fit for a custom app class.
I recommend sharing data between activies with extras. If it's a own class, it must implement Serializible.
If you are feeling lazy, go with Application's singleton pattern.
But, if you want to code smarter, go with Parcelable.

Android and passing nested ArrayLists via Bundles

How do you pass an instance of ArrayList<ArrayList<HashMap<String, String>>> from one Android activity to another via an instance of Bundle?
(I could use JSON strings. I'd like to know if there are better ways.)
Thanking you kindly in advance.
You can pass it as an extra in the Intent that you use to fire up the new activity. Since ArrayList implements Serializable, you don't have to do anything special to feed it to Intent.putExtra().
In general it is not good to pass too many or too large data between activities via Intents. It's better to store them somewhere centrally and pass a lightweight identifier or something like this, so the other activity can retrieve them from the store.
E.g. you can use an Application class to store these data. An application class is always available as long as you application is running. You get it from each Activity by calling the getApplication() method.

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

Categories

Resources