Android MVP-Architecture 如何使用 SQLiteHelper 在模型中调用数据库

Android MVP-Architecture How to make Database Calls in the Model with SQLiteHelper

我目前正在开发 Android 应用程序,我选择了 MVP-Arhitecture。 我现在的问题是,我需要从模型中的数据库中读取和写入一些内容,但是因此您需要引用上下文并且在视图中。我想知道,如何在不破坏 MVP 架构的情况下将上下文从视图获取到模型(如果可能的话)。

谢谢!!!

必须创建模型和演示者,即:

 new MyModel();
 new Presenter();

通常这是 Activity

 @Override
 public void onCreate(Bundle savedState) {
      Model model = new MyModel();
      Presenter presenter = new Presenter(model, this); // this being the View
 }

如果你在你的模型中使用数据库,你想使用一个依赖项来做到这一点,可能叫做 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
 }

现在您有一个名为 DatabaseReader 的 class,它通过构造函数将 Context 传递给它,因此您可以执行 "database things",而这个 class 本身被模型使用。

 public class DatabaseReader {

     private final Context context;


     public DatabaseReader(Context context) {
         this.context = context;
     }
 }

 public class MyModel implements Model {

     private final DatabaseReader db;

     public MyModel(DatabaseReader db) {
         this.db = db;
     }


 }