Question: 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](https://i.stack.imgur.com/VWoUa.png)](https://i.stack.imgur.com/VWoUa.png)

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*

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.
You can pass the context to ViewModel using Factory, for Example:

```
public class ViewModelClass extends ViewModel{
      private Context context;
      public ViewModelClass(Context context){
           this.context = context;
      }
}

```

and the factory class

```
public class ViewModelFactory implements ViewModelProvider.Factory{
private Context context;

    public ViewModelFactory(Context context){
    this.context = context;
    }
    @Override
        public <T extends ViewModel> T create(Class<T> modelClass) {
            if (modelClass.isAssignableFrom(ViewModelClass.class)) {
                return (T) new ViewModelClass(context);
            }
            throw new IllegalArgumentException("Unknown ViewModel class");
        }
   }

```

and when you used the ViewModel define the factory 

```
ViewModelFactory viewModelFactory = new ViewModelFactory(context);

```

then pass it like this:

```
viewModel = ViewModelProviders.of(this, viewModelFactory).get(ViewModelClass.class)

```