Intent.putExtras size limit?

我只是一个虾纸丫 提交于 2019-11-27 16:13:28

if both activities are yours, use a decent data model. Android doesn't encourage that much to very well designed application. Or turn it differently, it allows for fast developped application and doesn't promote much of good software application principle.

The solution of @Jean-Philippe Roy (québec ?) is interesting but singleton are quite an anti-pattern when it comes to more elaborate things, namely statefull models or serviceS.

The best option is to use an application class. This class is your singleton, by nature in android. So,

  • define an application class in your manifest
  • provide a static method to access the unique instance of the application class (it is always a singleton).
  • give it a method to receive and hold your data, call it from your first activity
  • and a second one to get them back in your second activity

---Updated after @straya's answer and 18 more month of Android programming :)

The question of sharing a data structure or processes accross application, activities, views, fragments is always present at mind when building Android application. It's important to know and consider that the application scope is the right place to hold shared structure, but using the application class itself to put a data structure in that scope is not viable with regards to :

  • code quality, if all shared data structures and process are know of the application, it will quickly become bloated with accessors for all those entities.
  • there is only one global shared pool of entities, which is not find grained enough and may lead to hard to detect ways of coupling entities

I now tend to prefer using Dependency Injection managed singletons. Dagger or RoboGuice both allow to create and inject a single instance of a given class into other classes. This technique, and DI more generally offers great possibilities for good Android designs :

  • don't degrade quality of code, it is even shortened quite a lot. Use @Inject to inject dependencies and they will get injected.
  • don't give 2 responsibilities to the singletoned class : it will not handle the singleton instance creation, the framework will do it.
  • it's easier to pass from a singleton to a normal instance
  • as those singletons become normal classes with a simple annotation, they do not contain static methods anymore and this allows to mock them very easily. And that's a big point.
  • and of course, DI annotations make it very clear when a class depends on another class, helping to self document code more.

Just in response to Snicolas' answer:

Application is already a Singleton, no need to "turn it to" one.

Personally, after some serious reliance on Application to hold data for a long time, I've come to not trust it entirely. I use self-caching data objects to mitigate the problems though ;)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!