Search code examples
javaandroidmvp

Creating a Basic MVP Android App


public class MainActivity extends AppCompatActivity {
    //text
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void sendMessage(View view) {
        //Grab input
        EditText editText = findViewById(R.id.editText);
        String message = editText.getText().toString();
        //Throw input onto the label
        TextView destinationText = findViewById(R.id.destinationText);
        destinationText.setText(message);
    }
}

This app has a user interface with a EditText, a Textview, and a button. The button will copy the text the user typed in the EditText object and place it in the TextView.

MVP and MVVM seem to be the most popular design patterns today.

In the spirit of learning one of these architectural design patterns, How could I adapt this most basic app to the MVP architectural pattern?


Solution

  • I'd definitely recommend a bit of research before starting any piece of code. Today Android offers many interesting app architectures, and even though it's not trivial to chose the best one that suits you, that journey will make you learn a lot.

    A good starting point for that is the Google's official architecture sample projects on GitHub. Not only you have many different architectures like MVP, MVVM, MVI, but also some interesting variants within each architecture.

    On the other hand, Android is doing a great work trying to simplify that creating a great collection of libraries. That's called Android Architecture Components, and here you have some of their samples to start playing and adopting their patterns.

    Finally, if you still decide to go with MVP, there're a few things you'll have to do in your example:

    1. Your MainActivity (the View) should implement a contract of that View (e.g: MainViewContract).
    2. Within that View, you should get the reference to your MainPresenter passing the reference of the View which implements MainViewContract.
    3. The MainPresenter will also implement a contract (e.g: MainPresenterContract).

    Basically all connections you need are stablished. The MainPresenter will be responsible of the business handling View inputs and outputs. In your case, the inputs and outputs very straightforward:

    Inputs (MainPresenterContract):

    • void copyText(String textToCopy);

    Outputs (MainViewContract):

    • void showCopiedText(String copiedText);

    When the user clicks the button, you'll send the message copyText through the presenter local instance. Then, the presenter will get that and perform the output invoking showCopiedText. Since the main view MainActivity implements the MainViewContract, you'll receive the output message in a local method of the view where you just paint the text on the Textview.