Skip to content
Advertisement

MVVM – get context in a Model class

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. mvvm

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.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement