CJStudio
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Android Architecture: MVP Pattern ###### tags: `Android Architecture` [TOC] ## What is MVP? ![](https://i.imgur.com/lCaQtYF.png =500x350) MVP stands for Model-View-Presenter. ### Each Part **Model:** It is the data layer, responsible for managing the business logic and handling network or database API. **View:** It is the UI showing the data obtained from model. The view will implement the interface the presenter has. Furthermore, it still needs an instance of the presenter. **Presenter:** The presenter is a controller that really does not know which view it is going to handle now nor after. It just sends the information to whoever request it. In order to achieve this attribute, it has an interface which is implemented by the Views, the presenter might handle. ### How it works? 1. Presenter will have an interface inside the class. 2. The Interface inside Presenter will be implemented by the Views ## MVP Coding Parts ### 1. Model #### Information Main Structure: ```java== import com.google.gson.annotations.SerializedName; public class Country { @SerializedName("name") public String countryName; @SerializedName("capital") public String capitalName; @SerializedName("region") public String regionName; } ``` #### Interface used in >Why is it ++*@GET("all")*++? That is because the url was: https://restcountries.eu/rest/v2/++**all**++[color=red] ``` java== public interface CountriesApi { @GET("all") Single<List<Country>> getCountries(); } ``` #### Retrieve information from API: CountriesService Class used Retrofit library to get information from the API. ``` java== public class CountriesService { public static final String BASE_URL = "https://restcountries.eu/rest/v2/"; private CountriesApi api; public CountriesService() { Retrofit retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build(); api = retrofit.create(CountriesApi.class); } public Single<List<Country>> getCountries(){ return api.getCountries(); } } ``` ### 2. View The view will be implementing the interface made in the presenter, in order to let it know which view it is dealing at the moment. As it is ++implementing++ the interface, we have to remember to overridethe methods. In this case **setValues** and **onRetry**. ```java== import android.content.Context; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import android.widget.Toast; import java.util.ArrayList; import studio.zc.androidarchitecture.R; import studio.zc.androidarchitecture.model.Country; public class MVPActivity extends AppCompatActivity implements MVPPresenter.viewDealer{ private RecyclerView rv_country; private MVPAdapter mvcAdapter; private MVPPresenter mvpPresenter; private Button btn_retry; private ProgressBar pb_bar; public interface onClickI{ void onClick(int i); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_mvp); setTitle("MVP"); this.rv_country = findViewById(R.id.rv_country); this.btn_retry = findViewById(R.id.btn_retry); this.pb_bar = findViewById(R.id.pb_bar); this.mvcAdapter = new MVPAdapter(new onClickI() { @Override public void onClick(int i) { Toast.makeText(MVPActivity.this, "" + i, Toast.LENGTH_SHORT).show(); } }); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false); this.rv_country.setAdapter(mvcAdapter); this.rv_country.setLayoutManager(layoutManager); mvpPresenter = new MVPPresenter(this); } //viewDealer Override Methods @Override public void setValues(ArrayList<Country> country) { this.mvcAdapter.setCountryList(country); this.btn_retry.setVisibility(View.GONE); this.pb_bar.setVisibility(View.GONE); this.rv_country.setVisibility(View.VISIBLE); } @Override public void onRetry(View view) { mvpPresenter.onRetry(); this.btn_retry.setVisibility(View.GONE); this.pb_bar.setVisibility(View.VISIBLE); this.rv_country.setVisibility(View.GONE); } @Override public void onError() { Toast.makeText(this, R.string.error_msg, Toast.LENGTH_SHORT).show(); this.btn_retry.setVisibility(View.VISIBLE); this.pb_bar.setVisibility(View.GONE); this.rv_country.setVisibility(View.GONE); } //Intent public static Intent getIntent(Context context){ return new Intent(context, MVPActivity.class); } } ``` ### 3. Presenter Inside the presenter we have to state an interface, which will be implemented by the view it is dealing at the moment. :::warning **Note:** There is a ++**big difference** here with the MVC++ and that is you do not need a reference as MVPActivity, but you need one as viewDealer(the interface). This means that whichever view is given, it can still run, get information and send it over. And when the view obtains the information, it will handle it. ::: ```java== import android.view.View; import java.util.ArrayList; import java.util.List; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.observers.DisposableSingleObserver; import io.reactivex.schedulers.Schedulers; import studio.zc.androidarchitecture.model.CountriesService; import studio.zc.androidarchitecture.model.Country; public class MVPPresenter { private viewDealer view; private CountriesService service; public interface viewDealer{ void setValues(ArrayList<Country> country); void onRetry(View view); void onError(); } public MVPPresenter(viewDealer view) { this.view = view; service = new CountriesService(); fetchCountries(); } public void fetchCountries(){ service.getCountries() .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribeWith(new DisposableSingleObserver<List<Country>>() { @Override public void onSuccess(List<Country> value) { ArrayList<Country> rv_list = new ArrayList<>(); rv_list.addAll(value); view.setValues(rv_list); } @Override public void onError(Throwable e) { view.onError(); } }); } public void onRetry(){ fetchCountries(); } } ``` ## Advantange & Disadvantages **Advantage:** * The ++Presenter++ is **NOT** bonded to the view like the MVC architecture where controller is highly bonded to the view. >**Main advantage?** You can swap views and use the same presenter for all of them. [color=pink] >**How?** The presenter has an interface which it does not know which View will implement it. Moreover, the presenter will have instance of the interface, meaning it can be switch with whichever view implements the interface.[color=orange] **Disadvantage:** * The View is still highly dependent on the presenter, as it has the instance of it. This means you can only use specific presenter for each view. * Presenter will update values as soon as values are obtained. >**Why is the last one a problem?** What if you are using an app, clicked something which it is still running and when you are doing something else the view is updated suddenly, it will ++**INTERRUPT the user experience**++. [color=red]

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Google Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully