I’m using MVVM to build my Android app and I need to connect the Model to a DB. Instead of Room I’m using the SQLiteOpenHelper and to make a connection to the DB I need the context. But since this is a non activity class I’m struggling to get it.
My current solution looks as follows but I keep getting a memory leak warning.
public class MyApplication extends Application { private static MyApplication mContext; @Override public void onCreate() { super.onCreate(); mContext = this; } public static MyApplication getContext() { return mContext; } }
Any better solution or best practice?
edit: not using Dagger
Advertisement
Answer
Your solution works but you break the Dependency Inversion
rule in MVVM pattern. So you should implement Dependency Injection
pattern using constructor injection or frameworks like Dagger
to pass the context
to your model layer. Your memory leak is because of breaking this rule too and by implementing Dependency Injection there is no need for global variables with multiple access in different layers which can cause memory leaks.