0
votes

Is it okay to initialize model in the View when you're using MVP Architecture in Android? Here is the View class for example:

public class ViewActivity extends BaseActivity {

@BindView(R.id.lastNameEdt)
EditText lastNameEdt;
@BindView(R.id.firstNameEdt)
EditText firstNameEdt;
@BindView(R.id.middleNameEdit)
EditText middleNameEdit;

User userModel; <-----

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_layout);

    userModel = new User();  
    userModel.firstName = lastNameEdt.getText.toString();

}

}

I would like to know what is the best approach / good practice when implementing MVP architectural pattern, especially for Android.

The reason why I initialized the model in the view it's because I want to pass it on another activity through intent. What do you think is the best? Is it still acceptable if I put the model on the View or should I put it on the presenter?

3

3 Answers

0
votes

In this example there is no best approach / good practice when implementing MVP if you are only trying to pass through an object by getting its values from the view's layout (ViewActivity). I would suggest to:

intent.putExtra(String, Serializable/Parcelable)

and set the params of the object there.

Hope that answers your question.

0
votes

The main thing that mvp do is, it separates data layer and view layer, if you are using model inside your view class then it means your view is directly communicating to data.

The best approach is to use model in presenter layer. If you want to pass data to model just add one more parameter of that to Presenter constructor.

    Presenter(View view,String data) {
        this.view = view
        this.data = data
    }
0
votes

One thing you can do is a dependency injection to your presenter with the object.

Example

View

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_layout);

    presenter = new Presenter(this,new User());

}

Then at your presenter, you can get that instance from the view, use it inside every logic you need to do with it inside your presenter, and then use methods from your presenter to get the information you need from that model.

Presenter

Presenter(View view,User user) {
        this.view = view
        this.user = user
    }

private String exampleMethod(){
return user.firstName + " " + " StackOverflow "
}

Here you will see that each time you instantiate your Presenter in your view, you have 1 instance of your model inside your presenter, so each time you want to get data to your view, just call the presenter for the data to be shown.

View

onCreate(){
...
presenter = new Presenter(this,new User());
presenter.exampleMethod();
}