Reputation: 1433
I'm currently working on an Android App and i choosed the MVP-Arhitecture. My Problem is right now, that i need to read and write something from the Database in the Model, but therefor you need a reference to the Context and that is in the View. I want to know, how to get the Context from the View to the Model without breaking the MVP-Architecture (if it is possible).
Thx!!!
Upvotes: 2
Views: 3521
Reputation: 76536
Something has to create the model and the presenter i.e.:
new MyModel();
new Presenter();
Usually this is the Activity
@Override
public void onCreate(Bundle savedState) {
Model model = new MyModel();
Presenter presenter = new Presenter(model, this); // this being the View
}
If you are using a database inside of your model you want to use a dependency to do this, maybe called DatabaseReader
@Override
public void onCreate(Bundle savedState) {
DatabaseReader db = new DatabaseReader(this); // this being context
Model model = new MyModel(db);
Presenter presenter = new Presenter(model, this); // this being the View
}
Now you have a class called DatabaseReader
that has a Context
passed to it through the constructor so you can do "database things", and this class itself is used by the model.
public class DatabaseReader {
private final Context context;
public DatabaseReader(Context context) {
this.context = context;
}
}
and
public class MyModel implements Model {
private final DatabaseReader db;
public MyModel(DatabaseReader db) {
this.db = db;
}
}
Upvotes: 8