In fact, you do not need a Context
itself. What you need is a reference to a class that extends SQLiteOpenHelper
.
Let's say, a class Database
:
public class Database extends SQLiteOpenHelper {
...
}
This class, in turn, needs a Context
.
There are several different ways you can pass a reference of this Database
to your model. You can create a static
method in your Application
class that returns you an instance of the Database
class.
public class MyApplication extends Application {
private static MyApplication sInstance;
@Override
public void onCreate() {
super.onCreate();
sInstance = this;
}
public static Database getDatabase() {
return new Database(getContext());
}
public static Context getContext() {
return sInstance.getApplicationContext();
}
}
You can do this in your Model (or Presenter and send it to Model):
MyApplication.getDatabase();
Although it works, I do not really like this approach. I do not think it's right to do this in the Application class.
So, you could have a class, say: Injection
. Where do you hold "DI in hand".
public final class Injection {
private Injection() {
throw new IllegalStateException(Injection.class.getSimpleName() + " cannot be instantiated!");
}
public static Database provideDatabase() {
return new Database(MyApplication.getContext());
}
}
Another alternative is if you use Dagger, for example, let it do the automatic dependency injection of the Database
class on your Model.