why we use private constructor in flutter sqlite databse - android

What is the use of this private constructor and why we instantiate it's object under the class.
DatabaseHelper._privateConstructor();
static final DatabaseHelper intance =DatabaseHelper._privateConstructor();

In general, we'll use a private constructor when we don't want things to be instantiated more than once. This lets us implement the singleton pattern:
https://www.geeksforgeeks.org/singleton-design-pattern/
In this case, we don't want multiple instance of the database. So, it'll instantiate the database if it hasn't already been instantiated, or it'll return the existing instance of the database if it has been instantiated previously.

It is a design pattern called the singleton pattern.
It's main purpose is to ensure that only one instance of that class ever exists in the application.
To ensure this purpose, the pattern implements techniques that have serious disadvantages. People are overusing it, sometimes using it as a justification as to why they have those disadvantages in their program that would otherwise be considered bad design. It has become an anti-pattern. See Why is Singleton considered an anti-pattern?.

In addition to given answers, it is Eager singleton, therefore once the class is initialized, the instance is also initialized, even the instance is not used. However still it has been instantiated only once.
See also Singleton lazy vs eager instantiation

As the other answers state, it's the singleton pattern. Here's a link that explains it more.

Related

How to manage dagger2 component creation and storage

A long time i have been struggling with dagger components.
At first i made Injectors class for each custom scoped component which contained static field either with WeakReference<Component> or just a Component, so that i always had an access to this component through static method.
But i think thats a pretty bad approach because WeakReference could be cleared so you will not get the same Component, as well as you can just forget to clear Component in static field.
I designed another approach when i have ComponentsHolder interface which is implemented by App and contains some methods to add, delete, and check if component exists in a HashMap<String, Component> inside the same App class.
So this approach combined with kotlin extensions for Context gave me a great opportunity to inject thing anywhere i have Context like this:
context.injector(Component::class) {
inject(this#ObjectWhereToInject)
}
So i mind maybe i doing something wrong? Or is there a better approach to store and retrieve dagger components?

Calling Firebase Analytic's getInstance() every time vs. storing instance as a static variable in Application class

I'm trying decide which of the following is the proper way to do this:
Calling FirebaseAnalytics.getInstance(Context) from every activity, fragment, and service that I'm logging an event from.
or
Calling FirebaseAnalytics.getInstance(Context) once from Application class and keeping it around as a public static variable. Then, from everywhere I need this I can call `MyAppClass.mFirebaseAnalytics.logEvent()'.
Will any of the above methods have a undesired impact on the events that are automatically collected and/or do either of those have an efficiency gain over the other?
Many thanks!
The documentation states:
public static FirebaseAnalytics getInstance (Context context)
Returns the singleton FirebaseAnalytics interface.
So I don't see any particular reason why you can't just have a singleton instance in your code.
There won't be any noticeable efficiency gains with either approach. If you're looking into the second option, it might be worth considering doing this with dependency injection and a simple wrapper around the analytics instance to increase the testability of your code.

Two activities access same variable

I was wondering if I have 2 activities that needs to update and access the same object . What would be the best way to do it? Should I use Application class? Or perhaps Static variable.. Etc?
Another option I can think of is putting it in a base class that both activities inherit. I will initialize the object from shared preferences during OnResume
If your object holds some kind of preference value, don't put it into a super-class. Make it static and/or use the singleton pattern and separate it from your application logic. This provides you with a more modular structure that will be easier to work with. The application class is probably overkill; singletons do the job most of the time. (The Android docs simply states: "There is normally no need to subclass Application.")
You can add it to a super-class, if it is a logical part of it though.
Don't forget to synchronize your object if it's going to be accessed by another/several thread(s).
There are different method to perform such requirement. Singleton is one of them. The other one is extending the application class. If you want a reference outlining all of these methods please see:
What's the best way to share data between activities?

Is it a good practice to declare Context in beginning of Activity

In my last project in the activities I had a lot of MyActivity.this provided to the methods requiring context, so I decided to make it like this in the beginning of the class
private Context context = ActivityStage2.this;
and then just pass context to object methods. So far it works ok, but is it ok at all to declare the Context like that? I mean does that always have the updated state of the MyActivity.this each time the context object is referenced?
You can do it but there is no point in doing it.
You basically "cache" the this reference to a field. The field initialization will run just before the constructor body, so every time the object is recreated the reference context will be updated. This works similarly to this, which points at this instance object.
Now why would you do that? Readability? It seems like you want to use it in inner classes, because you explicitly qualify it with: ActivityStage2.this. The java way to qualify the outer class reference from an inner class is well understood by programmers, and here the gain is little. One exception could be anonymous inner classes where you don't have the name of the inner class. In this case caching the reference to the Activity makes sense, but I'd rather use a final local variable instead of a field.
Another reason for doing this could be that you need only the Context interface instead of the ActivityStage2 interface: that makes sense theoretically but in practice I wouldn't do it without some other better reason.
Last thing: if you turn your field in a static one, you will indeed leak.
There is no problem to do this if you follow the two rules listed bellow:
Keep the reference in a instance member. If you use a static field, your Activity instance could never be recycled by the GC because your MainActivity class has a strong reference to the object. If you really need to do this, use a WeakReference.
Keep a reference to your Activity instance. Do not keep a reference to other activity due to the reasons I have just described above.
Otherwise it all depends on you and your code style :)

can Dagger be used to perform injection on a Content Provider?

I have recently been integrating Dagger into a project that uses ContentProviders. I create a single ObjectGraph instance in my custom Application object, and basically in each managed component:
Activity,
Fragment,
Service
... Then, I call getApplication(), downcast to my custom Application object, and force the injection through some custom implementation in my Application class. This seems to be the prescribed method of performing injection based on the samples I've seen posted by the guys at Square.
This pattern doesn't hold for ContentProvider instances though as their lifecycle isn't as predictably tied to the lifecycle of the Application object, ie ContentProviders can be, and as I'm observing frequently are, created before the Application object is created (for reasons I have yet to comprehend).
so... does anyone have a nice way of injecting ContentProviders using Dagger? I've so far made it by having an isInjected() call at the beginning of each of my ContentProvider's interface methods (insert, query, update, delete)... basically a hacky form of lazy initialization. But this seems far from ideal. Is there a more prescribed approach to injecting ContentProviders?
The Application subclass is just a convention since it's usually the first object created. Our apps do not have content providers which is why we use them. There's nothing that says you can't put it somewhere else.
You can just use the traditional singleton pattern for instantiating and holding a reference to the ObjectGraph.
public final class Dagger {
static ObjectGraph og;
static ObjectGraph og() {
if (og == null) {
og = ObjectGraph.create(..);
}
return og;
}
}
The first person to access will initialize the instance which will be used for the lifetime of the process.
If your content provider is in a different process than your main application this solution will still work. Or you could simply create the graph when your content provider is created since it will be the only consumer. Normal multi-process rules still apply, of course, so no instances will be shared with the other processes.

Categories

Resources