user1058210
user1058210

Reputation: 1689

Large public static variables in Android

Hey I'm making a quiz application and I need to pass an ArrayList of up to 100 "Question" objects from one activity to another. The Question objects have about 6 parameters to them - all pretty small strings. I was looking up ways to do this and one of them mentioned was to declare it as a public static variable in one class and then reference it in another. I was wondering about the following:

Upvotes: 1

Views: 379

Answers (2)

user931366
user931366

Reputation: 694

I don't think you want to read static data from one activity to another, it's a solution that will undoubtedly lead to problems/side effects. It's better to keep activities as decoupled as possible.

I believe best solution (as offered above) is to make your Questions class Parcable. And then set the data in the Activity Intent.setExtra method. When your other activity starts you read the questions from the Intent and then all your data fits nicely within the lifecycle of activites and your activities are more reusable this way.

Upvotes: 0

Peter Knego
Peter Knego

Reputation: 80340

Answers:

  1. You need to instantiate it before you "use" if. By "use" I mean call methods on it. It does not matter where you instantiate it, first or second activity.

  2. Static fields are also called class fields, because they are accessed via class not via object instance. The result is that, in case of static fields, you have always only one instance, e.g. MyClass.someField is available in whole app and there is only one of it.

  3. It uses memory (RAM) as opposed to data in a file (uses flash storage). But, at some point you need to have it in memory, so it uses this memory in any case.

  4. Yes, if you only need it temporarily, you can set the field to null after you no longer need it and the memory will be freed (eventually, when gc runs).

BTW, there are several options to share data inside the app.:

  1. Pass data between activities via Intent.setExtra()/Intent.getXXXExtra()
  2. A class with static variables
  3. Via named Application class, which is single-instance and alive throughout app lifecycle
  4. Shared preferences
  5. Database
  6. Internal storage

Upvotes: 4

Related Questions