Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a reference within Android application? [duplicate]

I know there's simple mechanism to pass object between activities. I usually use Bundle and putParcelable() or put Serializable(), but I know that it's actually passing raw data by packing and unpacking objects, without keeping references.

But now my problem is different - I need to pass reference to some services and other activities. Is there any way do do it?


Maybe I explain my issue on real problem:

  1. I have a simple class City, which stores among other things weather data.
  2. I keep it in ListFragment and display it there.
  3. I also have fragment with GoogleMap, which shows Cities on list with weather.

How should I store cities: List<City> in my application?

like image 637
Kamil Lelonek Avatar asked Jan 18 '26 08:01

Kamil Lelonek


1 Answers

I need to pass reference to some services and other activities

No, you do not. You need to allow "some services and other activities" to have access to the same data. Passing by reference would be one way to achieve this end, but it is an approach not generally used in Android, just as it is not generally used in a Web app (pages do not pass JavaScript objects to other pages, for example).

The typical approach is to have a central data model, such as a singleton managing a bunch of POJOs, backed by a database. Then, you are passing identifiers around in Android, and those identifiers are usually simple values (ints, strings, etc.).

like image 52
CommonsWare Avatar answered Jan 19 '26 23:01

CommonsWare