【问题标题】:Android MVP-Architecture How to make Database Calls in the Model with SQLiteHelperAndroid MVP-Architecture 如何使用 SQLiteHelper 在模型中进行数据库调用
【发布时间】:2016-08-22 07:02:49
【问题描述】:

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

谢谢!!!

【问题讨论】:

    标签: android architecture mvp


    【解决方案1】:

    有些东西必须创建模型和演示者,即:

     new MyModel();
     new Presenter();
    

    通常这是活动

     @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 的类,它通过构造函数将Context 传递给它,因此您可以执行“数据库操作”,并且该类本身由模型使用。

     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;
         }
    
    
     }
    

    【讨论】:

    • 这是 MVC。 MVP 不应从视图中引用模型
    • 也许,尽管答案中没有提到视图。延伸阅读:blog.blundellapps.co.uk/…
    猜你喜欢
    • 2016-10-02
    • 1970-01-01
    • 2018-12-23
    • 1970-01-01
    • 2013-03-28
    • 1970-01-01
    • 2012-09-23
    • 2016-03-03
    • 1970-01-01
    相关资源
    最近更新 更多