Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data Sharing Between Android Activities

Tags:

android

I have a question that has been bugging me for a while now. I would like to know what is considered the canonical, or best practice, means of getting data from one activity to another. I am personally aware of two ways to do this. The first way is by bundling the data directly into the Intent via the putExtra() function (or something similar). However, this way seems to me to be a bit of a violation of encapsulation principles. The second way I have done this is by placing the data into a separate class, and sharing that class between the two activities. This seems to be more fundamentally sound, but I am still unsure. Anyone care to shed some light on this?

like image 735
John Roberts Avatar asked Mar 02 '26 17:03

John Roberts


1 Answers

I've had the same question when wrighting my app and I ended up creating my CustomApplication class that extends Application class and adding it to the tag in my AndroidManifest.xml. This way I can store any types of data inside it with proper getters and setters. Calling (CustomApplication).getApplicationContext() will return CustomApplication object, which is unique for your whole app and exists in single instance(singleton) and using which you can set and get necessery values.

The benefit is that your Application object and data within it exists as long as any part of your app(Activities, Services, etc) is running.

like image 145
Anton Cherkashyn Avatar answered Mar 05 '26 07:03

Anton Cherkashyn