I'm fairly new in Android/Java programming, so some of the basic stuff is still quite confusing. So, lets say my application gets all data (articles) it requires from external XML files, it parses them to data models (Article class) and those articles will be used (displaying in lists or single article) all over the application for all it's lifecycle.
Where should I keep them? Can I create singleton class with an array containing all the articles I've parsed? Or should I save them to database and then query it on demand? (that sounds like too much work, I don't need to cache them for now) What's the best practice here?
Keep them in Application. This is a base class of any android application and it's alive during the whole lifetime of the application, whereas Activities are killed when not shown or orientation is changed.
You have to declare android:name
in your AndroidManifest.xml:
<application android:name=".YourApplication"/>
Edited:
This is also relevant: How do I pass data between Activities/Services within a single application?
that depends what is your programming style lol.
you can as you said create a singleton that will read your xml and store everything.
you can create a static hash in your class. this way when you create a new object you will have access to the static information from that class.
you can pass the information from class to class as parameters.
if you want us to tell you which one would be the best it will be difficult without knowing the architecture of your program.
for example you could have a view controller that handle any changes and then it is simple to store the data at that level to pass it on when you switch views.
you could have static views in wich you could directly set all the values as you open them.
you could have losely linked views that call each other without any controller to handle the switching and in that case you would may prefer having a way to collect the info you need from a singleton or a static method...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With