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?
- is this a very memory-consuming method? Is there a more efficient but relatively straight forward way?
- if I declare the variable null after I finish using it, it will free up all the space that was previously being used right?
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.someFieldis 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
nullafter 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()Applicationclass, which is single-instance and alive throughout app lifecycle