Model receive context in Android MVP

2

I have a sqlite database, to use precise context, however, sending the context to the presenter and then pro model would be a violation of MVP, since it is part of the view, it is part of Android. How would I use context without violating MVP?

In this case, pass pro presenter would look like this:

interface Model {
    String getUser();
    String getPassword();
}

interface View {
    void showToast(String message);
    void emptyUsuarioEditText();
    void emptyPasswordEditText();
    Context getContext();
}

interface Presenter {
    void login(String user, String password);
    Context getContext();
}
    
asked by anonymous 27.09.2017 / 22:28

1 answer

2

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.

    
28.09.2017 / 19:53