Reputation: 1689
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:
Do I need to "instantiate" the ArrayList before I can use it or can I just declare the variable? As in:
ArrayList<Question> QuestionBank = new ArrayList<Question>();
or
ArrayList<Question> QuestionBank;
if i'm declaring this variable in one activity how does it stay available when I'm in the other activity? Is the activity it was declared in kept running?
Upvotes: 1
Views: 379
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
Reputation: 80340
Answers:
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.
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.
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.
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.:
Intent.setExtra()
/Intent.getXXXExtra()
Application
class, which is single-instance and alive throughout app lifecycleUpvotes: 4