Currently, I have a database manager class that handles all operations to the database like this:
class DatabaseManager(val context: Context) {
private val db = Firebase.firestore
//Other functions, etc.
}
It makes use of the context passed in by different activities to perform functions to the database. The thing is, every single activity that requires database functions have to instantiate this manager class first, then call the functions. I would like to make use of the Singelton design pattern to make it such that all the activities will only use a single instance of the class. I believe kotlin's objects can do this, however I also need to be able to pass in the context of the activities into this manager class. Any assistance is appreciated, thank you!
I would recommend not doing that. The problem with Singletons is that they make code hard to test, you can't fake out the database. And for a database this is a particularly bad problem, as setting up all the right fake data can be painful. Instead, take a look at injection. It can do the same thing (make a single instance shared between everyone who needs it), but it manages that global state rather than having the classes themselves manage it via a static reference, passing it in (generally via the constructor) to whoever needs it. This makes it easy to provide an alternative or mock database when needed for testing. Injection used to be a bit painful to set up, but Hilt makes it a lot easier these days.
Related
I have one Activity and i have created one View-model for it. I have created different classes like
UiUtil( show, hide view, hide key board ), Network layer , Data Base layer, AppUtil( for common functionality like Collection check, String validation, Date Conversion etc)
My question is, In MVVM design pattern is Activity can use these utility classes directly or it needs to use these classes via View-model, if it via view model then in the view-model i have to write a method that just call utility classes method . like below TimeDateManager is utility class used in view-model
class HomeViewModel: BaseViewModel()
{
fun prepareTimeAmPmToDisplay(context: Context, alarm: Alarm): String
{
return TimeDateManager.prepareTimeAmPmToDisplay(context, alarm)
}
}
Architectures are not obligatory, they are recommendational, thus you can change their usage in quite wide range. The only stopper should be a common sense(if it is present of course).
In this particular case the usage of utility class inside an Activity maybe ok, based on your ViewModel construction and its way of communication with View(read Activity).
For example if you have some LiveData that sends some kind of event(for ex. data loaded from backend or alarm trigger) inside your ViewModel and your View listens to it, I think it is ok to use util classes inside an Observer in Activity. Especially if this utils method doesn't depend on any ViewModel or Repository data. The direct utils usage in Activity is not limited by this usecase, though - there are plenty of others.
I understand that this may be an unpopular opinion in modern time of "clean approach" but I believe that this "clean approach" sometimes complicates stuff where it shouldn't, thus if mixing things a bit does not brake overall architecture but rather makes some thing more readable and easy to maintain - I would go for it.
Hope it helps.
My approach toward MVVM is simple, ViewModel is responsible for business logic, dealing with repositories (Network, Database, etc.) and all of the non-UI codes preparing the required data for UI, just like the documentation:
A ViewModel object provides the data for a specific UI component, such as a fragment or activity, and contains data-handling business logic to communicate with the model. For example, the ViewModel can call other components to load the data, and it can forward user requests to modify the data. The ViewModel doesn't know about UI components, so it isn't affected by configuration changes, such as recreating an activity when rotating the device.
On the other hand, ViewModels should not store a context (ApplicationContext is exceptional) and it's preferred that they do not use android APIs at all, so they become more testable (especially in the case on pure unit tests).
Also we are recommended to make use of LiveData in ViewModels and the UI has to observe the LiveData. For example, in onCreate of your Activity, you will call loadMainContent() method from VM, it calls getMainContent(page=1) from repository, and the repository will decide to load data from DB or network, and the result will be set on a LiveData were the View is listening for changes.
TL;DR
Sometimes it's even better to call these utilities from View rather than the VM. I'm pretty sure about your UiUtil also I think TimeDateManager is more view related rather than logic related. In addition, Network and DB layers are more efficient if called through a repository (which is responsible for caching, etc.) and VM can use that repo.
I'm working on an Android app that uses some background tasks (AsyncTasks) and I want to use best practices regarding data persistence across app lifecycle and tasks callbacks.
Up to now, I have a mix of practices regarding this:
1) I have some static fields in classes where AsyncTasks are used in the form of:
private static String str1;
private static String str2;
private static int int1;
...//=>no more than 6 static fields
2) I use a sinleton App instance with many getters/setters in the form of:
package xxx.xxx.xxx
import xxx.xxx.xxx
...
public class AppSettings {
private static AppSettings singleton;
private String _field1;
...//=>many fields
public void setField1(String field1) { _field1 = field1; }
public String getField1() { return _field1; }
...//=>many getters/setters
private AppSettings() {}
public AppSettings getInstance(){
if (instance== null) {
synchronized(AppSettings.class) {
if (instance == null)
instance = new AppSettings();
}
}
return instance;
}
}
I definitely know that abusing of static fields is not good at all, so I decided to replace them all, but I'm not completely sure if my second approach -having an application instance in a singleton with many getters/setters- is considered a good way to go, and in case not, I would like to know about better alternatives.
Thank you very much.
Edit 1: Just to clarify.
In order for you to understand more clearly what I use my AppSettings singleton class for I'll give you two examples:
1) I use it to store app setting/configuration values (that's why the name) to be available anywhere. For example, font color, font size, whatever.
2) I use it to store temporary data/values. For example, my main activity creates a small video in the backgroung using "VideoHelper" class and called through an AsyncTask, and as video generation process needs some parameters from main activity, I use AppSettings getters/setters to send them through.
Edit 2: Better explanation of everything.
Thanks to #a_local_nobody I realized my "case of use" was not so clear so I'll add a few things more.
My AppSettings is not being used to store user settings, I use SharedPreferences for that, but instead app default configuration parameters.
To give an example, I store activities background color (and this is just an example) so if in the future I change my mind and decide to use another background color this setting (and many more) are centralized there. It's like a "container" for many default app settings.
Regarding the use of getters and setters in this app singleton class, I think I'll foloww #a_local_nobody suggestion related to define some static variables in each class and use them as needed instead of having a bunch of unrelated getters/setters globally.
Anyway, all comments are welcome.
Well, you are talking about persisting data across app lifecycle which, in my mind, sounds like you're looking for a ViewModel:
The ViewModel class is designed to store and manage UI-related data in
a lifecycle conscious way. The ViewModel class allows data to survive
configuration changes such as screen rotations.
as well as:
The purpose of the ViewModel is to acquire and keep the information
that is necessary for an Activity or a Fragment. The Activity or the
Fragment should be able to observe changes in the ViewModel.
ViewModels form part of the MVVM design pattern, with loads of examples available online.
For more info, have a look at the documentation
on a side-note, perhaps you can have a look at the google sunflower project for some ideas on how to implement the new architecture components, which includes usages of ViewModels.
Also worth adding, is that what you've created with your AppSettings solution, is a big dependency. Various things will depend on this single object and it will be needed throughout your application, most likely. You might consider, instead of creating it like this, to rather use dependency injection with your options, for android, probably being either Dagger 2 or Koin for kotlin (if you ever swap over to kotlin) or perhaps your own form of dependency injection without having to use these frameworks.
Hope this helps
Edit based on feedback from OP:
I use it to store app setting/configuration values (that's why the
name) to be available anywhere. For example, font color, font size,
whatever.
this sounds like a better use case for Shared preferences, especially if these are settings defined by a user, otherwise you should be savings these into strings.xml etc. and making use of localization
I use it to store temporary data/values. For example, my main activity
creates a small video in the background using "VideoHelper" class and
called through an AsyncTask, and as video generation process needs
some parameters from main activity, I use AppSettings getters/setters
to send them through.
if you have a VideoHelper class, you might be better off either creating a Builder design pattern for this object, or having static variables for this helper to change its functionality as you need to, if these are variables for your VideoHelper, then they should be located with your VideoHelper.
Things which change together should usually stay together.
Your approach doesn't qualify as "best practices" in modern android development.
The recommended way of handling configuration changes is by using the new architecture component: ViewModel
It have the property of surviving the onDestroy triggered when a configuration change occurs.
Basically, you will need to move this AppSettings code to a ViewModel.
I have this code which provides the logic of this solution, but I'm aware that collecting an instance from within the constructor is dangerous.
Does anyone know a better solution?
The goal is to collect all instances that are extending this class. My preferred solution is the one the uses as little resources as possible (libraries, cpu, ram) although I know that there will always be a tradeoff.
I've tried something with reflection, annotation, classpath search but non of them seemed to be the silver bullet.
class Parent{
private companion object{
var childs = arrayListOf<Parent>()
}
constructor(){
childs.add(this)
}
}
If the intention is to collect all instances you should anyway somehow get those instances upon their creation (will it be the constructor or factory method, if any). Also you should somehow store them (maybe LinkedList is a better choice). So your approach seems reasonable.
But remember that within this approach these instances will be linked from a static place, which means that they wouldn't be garbage collected. If you don't want that, you could store them using a WeakReference (more precisely a collection of WeakReference<Parent>'s).
In the context of developing and android app, should I use presenters directly in views using 'new' or would it be better if I injected them to the view.
Pros/cons for not using injected presenters:
Faster development time, without having to write components and modules.
Presenters are tightly coupled with the views, I don't see this as much of a problem as most of the time presenters are not shared across multiple views(ie. one single view for a presenter).
Might be a problem for testing, as with using dependency injection mock implementations of the presenters can be provided(not sure if this is any useful, need more insight on this).
You're right. Using injection will only help you in the long run. You could either spend 5 minutes setting up your module / component, or you could be just coding.
As long as you don't do proper testing, there is not much difference to it, if you presenter looks like the following
mPresenter = new Presenter();
Assuming you use constructor injection properly, after creating your component, you save some lines as compared to
#Inject Presenter mPresenter;
// onCreate or some other place
{
getComponent().inject(this); /* getComponent() also 4-5 lines */
}
Again. If you use proper constructor injection there is a good chance you don't have many module code. Just creating some component will do.
But you saved some minutes and once you want to do testing this is just some easy refactoring, which can quickly be done.
So why Dagger?
This was assuming your presenter has no dependencies on other objects. But what if it does?
SharedPreferences preferences = getPreferences();
MyStorage storage = new MyStorage(preferences);
mPresenter = new Presenter(storage);
Using something to store your data is properly a good use case. While you just added some more logic about object creation to your activity, the dagger implementation would still look the same.
Even more?
Now let's assume you want to share this storage from above between activities. Now you have to add some logic to your Application or in some other place where you can create a Singleton to use throughout your app.
This will probably not be your only singleton, though, and you will start to clutter up your Application as well. Don't get me started on managing those objects lifecycle, e.g. user logging in or out, make sure to clear that cached data!
Again. The dagger implementation still looks the same. If there is some more logic needed it is well placed in the modules and abstracted with component dependencies.
Once you start thinking I could just create classes that handle object construction and injection you know that you could have just used dagger in the first place ;)
I also wrote a blog post about dagger basics including how constructor injection works, which many beginners are not using properly for some reason.
There are many questions and answers on how to implement a global variable in Android/Java.
So it seems one can either implement a singleton or use a data class itself with static variables.
I am about to start a larger project and would like to start on the right foot.
I am just not sure which one to use.
Pro singleton/con Data Class
supposedly "cleaner" way (but I really don't know why)
ensures that there is really always just one representation
creates a new instance should the old one be "cleaned away" (whenever this may happen?)
Con singleton/pro Data Class
not recommendet by some (but did not find convincng reasons)
ensures that there is only one representation by design
very easy to access just by writing MyDataClass.x (vs accessing singleton requires getting access to it first somehow)
no need to pass it as a parameter
So in summary I tend to use DataClass but I am unsure because I read that this is supposedly not good programming style.
I like to add
the data this global object has to hold is quite big, more than 30k strings/keys. And this should not be cleaned at any stage so that when the app return it may crash because of that - as I read in other places eg Singletons vs. Application Context in Android? (the 3rd answer)
it's not a web application, I use only one classloader
it is multithread but only one thread is actually accessing this data
one may certainly also use this approach How to declare global variables in Android?, but isn't an ObjectClass just easier to use and access in this case?
And checking this http://developer.android.com/resources/faq/framework.html, esp under "Persistent Objects", implies that there is no real advantage for on or the other in those cases anyway.
Many thanks
Best way to implement singleton is to use enum.
public enum Singleton
{
INSTANCE;
public void someMethod()
{
// your code here
}
}
For more details you can read Effective Java (2nd Edition)
First of all: There's not much difference between a class with public static member variables and a singleton class. A lot of developers prefer the singleton pattern because the code looks more natural and more Java. E.g. Singleton.Data looks like a constant access and Singleton.getData() looks like you're accessing some kind of static data.
Personally I use the static Application pattern: See Accessing resources without an Activity or Context reference
You can use onCreate to setup any kind of static data or even other singletons. E.g. I prefer to setup a singleton SQLite database like that and access it then via App.getDb(). You can use this pattern to access the application context or resources.
While using static data you should think about memory leeks. I would recommend to take a look at this article then.