Search code examples
androidmvpandroid-mvp

Where should I do activity navigation in MVP architecture?


I have an Android project which was built using the MVP architecture. One thing that I'm not quite sure of is that when I want to navigate to another activity after clicking on a button for example, should I place

startActivity(intent) 

inside the view component or inside the presenter component?


Solution

  • You have to do this in view component all the ui related activities must be performed in views like open new activity or replacing fragment and asking for permissions.

    Let me explain you further suppose we have a single button in our activity so we will write its logic in presenter i.e call a presenter method buttonClick() and if we want to open another activity after our logic we simply call getMvp.openMainActivity(); where as openMainActivity()will be the part of view.

    Here is a example methods for basic login activity based on MVP architecture. My Login Presenter MVP interface have

      void onServerLoginClick(String email, String password);
    

    My Login View MVP interface have

    void openMainActivity();
    

    My Login Presenter implementation is

    @Override
        public void onServerLoginClick(String email, String password) {
            //validate email and password
            if (email == null || email.isEmpty()) {
                getMvpView().onError(R.string.empty_email);
                return;
            }
            if (!CommonUtils.isEmailValid(email)) {
                getMvpView().onError(R.string.invalid_email);
                return;
            }
            if (password == null || password.isEmpty()) {
                getMvpView().onError(R.string.empty_password);
                return;
            }
            getMvpView().showLoading();
    
    
            User u   = getDataManager().matchUser(new User(2l,"",email,password,"",""));
            if (u==null){
                getMvpView().onError("No user found");
                getMvpView().hideLoading();
    
    
            }else {
                getDataManager().updateUserInfo(
                        "",
                        u.getId(),
                        DataManager.LoggedInMode.LOGGED_IN_MODE_SERVER,
                        u.getName(),
                        u.getEmail(),
                        "",
                        password);
                getMvpView().hideLoading();
                getMvpView().openMainActivity();
            }
    
    
    
    
        }
    

    my Login View class implementations is

    @Override
        public void openMainActivity() {
            Intent intent = MainActivity.getStartIntent(LoginActivity.this);
            startActivity(intent);
            finish();
        }
    

    Hope this will help you to understand the concept.