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: 
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)

```
If you read the [View Model Documentation](https://developer.android.com/reference/androidx/lifecycle/ViewModel)
you will notice the very first line mentions [Known direct subclasses
AndroidViewModel](https://developer.android.com/reference/androidx/lifecycle/AndroidViewModel) which in turn has a public constructor that accepts the Application Context. Quote from the documentation:

> 
> Application context aware ViewModel.
> Subclasses must have a constructor which accepts Application as the only parameter.
> 
> 
>