androidfragmentmvppresenter

Android MVP: defining Presenter in Fragments


I have done lot of search on Google and also on Stackoverflow but still I'm confused, so asking a question here.

I have this small MVP design pattern -

SigninView.java

public interface SigninView{

    void onSuccess();
    void onError();
    void onComplete();
}

SigninPresenter.java

public interface SigninPresenter {

    void signIn(String emailID, String password);
}

SigninModel.java

public class SigninModel implements SigninPresenter {

    private SigninView mSigninView;

    public SigninModel(SigninView mSigninView) {
        this.mSigninView = mSigninView;
    }

    @Override
    public void signIn(String emailID, String password) {

        if(emailID.equals("abc@example.com") && password.equals("123")){
            mSigninView.onSuccess();
        }
        else{
            mSigninView.onError();
        }

        mSigninView.onComplete();

    }
}

I want to implement the SigninView on a Fragment and define the SigninPresenter there itself like this -

SigninPresenter mSigninPresenter = new SigninModel(view_of_mvp);
mSigninPresenter.signIn("adadada", "asads");

See one reference here. I want to implement a View and define a Presenter like this but on a Fragment - https://github.com/ashokslsk/Comprehensive-MVP/blob/master/app/src/main/java/com/ashokslsk/mvpexample/MainActivity.java

How to achieve that ?


Solution

  • You don't actually need to pass the context, but rather the implementation of your SigninView. So you need to make your fragment implement SigninView

    MyFragment implements SigninView
    

    and simply initialize the presenter with this, instead of context. In fact, you presenter shouldn't know much about the Android SDK, so it shouldn't deal with contexts. See this answer.

    SigninPresenter mSigninPresenter = new SigninModel(this);
    

    EDIT:

    You had the activity like this:

    public class MainActivity extends AppCompatActivity implements SigninView 
    

    All you have to do is make your fragment implement SigninView:

    public class MyFragment extends Fragment implements SigninView 
    

    And then, in onCreateView you can initialize the presenter like this:

    signinPresenter = new SigninPresenterImpl(this);