Use of the Framework pattern MVC in Android

Source: Internet
Author: User

Use of the Framework pattern MVC in Android

I have been learning about Android development for two years. During these two years, I have mastered the basic knowledge of Android. The more difficult it is to learn later, the more difficult it is to think that android has nothing to learn (in fact, there is still a lot of knowledge and science ), secondly, many frameworks on the network have already helped us with too many things. We only need to draw the UI and feel that there is not much gold in Android development. I have nothing to worry about recently. I started to summarize the previous knowledge points and thought about whether I should learn other things? It cannot be limited to basic Android knowledge. Slowly exploring and discovering that a good framework and a good design model can reduce the workload of large projects. So the next two blogs will learn about the two common framework design patterns in Android: MVC and MVP.

MVC Concept

The full name of MVC is Model View Controller, short for model-view-controller. It is a Model of software design, organize Code by means of separation of business logic, data, and interface display, and integrate the business logic into a component to improve and personalize the custom interface and user interaction, you do not need to rewrite the business logic. Among them, the M layer processes data and business logic; the V layer processes the Display Results of the interface; the C layer serves as a bridge, to control the communication between the V layer and the M layer to achieve the separation of View display and business logic layer. After talking so much about it, I feel very abstract. I don't talk much about it. Let's take a look at how MVC is applied in Android development!

MVC for Android

In Android development, the most popular development framework pattern adopts the MVC Framework pattern. The advantage of using the MVC pattern is to facilitate the display of part of the UI interface and separate the business logic and data processing. What code does the Android project use to act as M, V, and C?

M layer: Suitable for some business logic processing, such as database access operations, network operations, complex algorithms, and time-consuming tasks. V layer: The data displayed at the application layer. XML layout can be regarded as V layer, displaying the data results at the Model layer. Layer C: In Android, the Activity processes user interaction issues, so it can be considered that the Activity is a controller, and the Activity reads data from the V view layer (eg. reads the data of the current EditText control. editText control data input), and send data requests to the Model (eg. initiate a network request ).

Next we will use a small project to get weather forecast data to interpret MVC for Android. First, the interface is shown as follows:

Controller
Package com. xjp. androidmvcdemo. controller; import android. app. dialog; import android. app. progressDialog; import android. OS. bundle; import android. support. v7.app. actionBarActivity; import android. view. view; import android. widget. editText; import android. widget. textView; import android. widget. toast; import com. xjp. androidmvcdemo. r; import com. xjp. androidmvcdemo. entity. weather; import com. xjp. androidmvcdemo. entity. weatherInfo; import com. xjp. androidmvcdemo. model. onWeatherListener; import com. xjp. androidmvcdemo. model. weatherModel; import com. xjp. androidmvcdemo. model. weatherModelImpl; public class MainActivity extends ActionBarActivity implements OnWeatherListener, View. onClickListener {private WeatherModel weatherModel; private Dialog loadingdiener; private EditText cityNOInput; private TextView city; private TextView cityNO; private TextView temp; private TextView wd; private TextView ws; private TextView sd; private TextView wse; private TextView time; private TextView njd; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); weatherModel = new WeatherModelImpl (); initView ();}/*** initialize View */private void initView () {cityNOInput = findView (R. id. et_city_no); city = findView (R. id. TV _city); cityNO = findView (R. id. TV _city_no); temp = findView (R. id. TV _temp); wd = findView (R. id. TV _WD); ws = findView (R. id. TV _WS); sd = findView (R. id. TV _SD); wse = findView (R. id. TV _WSE); time = findView (R. id. TV _time); njd = findView (R. id. TV _njd); findView (R. id. btn_go ). setOnClickListener (this); loadingDialog = new ProgressDialog (this); loadingDialog. setTitle (loading weather ...);} /*** display result ** @ param weather */public void displayResult (Weather weather) {WeatherInfo weatherInfo = weather. getWeatherinfo (); city. setText (weatherInfo. getCity (); cityNO. setText (weatherInfo. getCityid (); temp. setText (weatherInfo. getTemp (); wd. setText (weatherInfo. getWD (); ws. setText (weatherInfo. getWS (); sd. setText (weatherInfo. getSD (); wse. setText (weatherInfo. getWSE (); time. setText (weatherInfo. getTime (); njd. setText (weatherInfo. getNjd ();}/*** hide progress dialog box */public void hideLoadingDialog () {loadingDialog. dismiss () ;}@ Override public void onClick (View v) {switch (v. getId () {case R. id. btn_go: loadingDialog. show (); weatherModel. getWeather (cityNOInput. getText (). toString (). trim (), this); break ;}@ Override public void onSuccess (Weather weather) {hideLoadingDialog (); displayResult (weather) ;}@ Override public void onError () {hideLoadingDialog (); Toast. makeText (this, failed to get weather information, Toast. LENGTH_SHORT ). show ();} private
  
   
T findView (int id) {return (T) findViewById (id );}}
  

The code above shows that the Activity holds the WeatherModel object. When a user clicks a Button to interact, the Activity reads data from the EditTextView of the View layer as the Controller control layer, then, initiate a data request to the Model, that is, call the getWeathre () method of the WeatherModel object. After the Model processes the data, the OnWeatherListener interface is used to notify the View layer that the data is processed. The View layer updates the UI. The View layer then calls the displayResult () method to update the UI. So far, the entire MVC Framework process has been reflected in the Activity.

Model

Let's take a look at the WeatherModelImpl code implementation.

Package com. xjp. androidmvcdemo. model;/*** Description: Request network data interface * User: xjp * Date: 2015/6/3 * Time: */public interface WeatherModel {void getWeather (String cityNumber, onWeatherListener listener );}................ package com. xjp. androidmvcdemo. model; import com. android. volley. response; import com. android. volley. volleyError; import com. xjp. androidmvcdemo. entity. weather; import com. xjp. androidmvcdemo. volley. volleyRequest;/*** Description: This interface is used to obtain weather information from the network. * User: xjp * Date: 2015/6/3 * Time: 15: 40 */public class WeatherModelImpl implements WeatherModel {@ Override public void getWeather (String cityNumber, final OnWeatherListener listener) {/* data layer operation */VolleyRequest. newInstance (). newGsonRequest (http://www.weather.com.cn/data/sk/ + cityNumber +. html, Weather. class, new Response. listener
  
   
() {@ Override public void onResponse (Weather weather) {if (weather! = Null) {listener. onSuccess (weather);} else {listener. onError () ;}}, new Response. errorListener () {@ Override public void onErrorResponse (VolleyError error) {listener. onError ();}});}}
  

The code above shows that a WeatherModel interface is designed here, and then the WeatherModelImpl class is implemented. The controller activity calls the method in the WeatherModelImpl class to initiate a network request. Then, the OnWeatherListener interface is implemented to obtain the network request result and notify the View layer to update the UI. Now, Activity isolates View display from Model data processing. Activity acts as contronler to complete the coordination between model and view.

Why is it not directly designed as a getWeather () method in the class to directly request network data? You should consider this situation: the network requests in the Code are implemented using the Volley framework. If the boss wants you to use the Afinal framework to implement network requests someday, how can you solve the problem? Is it the implementation of modifying the getWeather () method? No. This modification not only damages the previous code, but also is not conducive to maintenance. Considering the extension and maintainability of the Code in the future, we chose the interface design method to solve a problem, we implement another WeatherModelWithAfinalImpl class that inherits from WeatherModel and overwrites the method in it. This not only preserves the previous WeatherModelImpl class request network method, but also adds the WeatherModelWithAfinalImpl class request method. No modification is required for the Activity call code.

MVC usage Summary

Using the MVC design pattern, this small weather forecast project has good scalability and maintainability. When you need to change the UI display, you do not need to modify the contronler Activity code and Model) the business logic code in the WeatherModel model separates the business logic from the interface display.

In the Android project, business logic and data processing have assumed the role of Model, XML interface display, View, and Activity as the controller. The Controller acts as an intermediate Bridge. It communicates with views and models through interface communication.

When is the MVC design pattern applicable? Of course, a small project does not need to be designed using the MVC framework without frequent modifications. Instead, it feels that the code is over-designed and the code is bloated. Generally, in large projects, the business logic processing is complicated, and there are many page displays. It is advantageous to use MVC for projects that require modular design.

4. in the MVC mode, we found that the controller Activity mainly decouples the View from the Model. Although the Activity interacts with each other, however, there are a lot of display code about the View UI in the Activity. Therefore, the View and the Activity controller are not completely isolated. That is to say, some View views and the contronler controller Activity are bound to a class.

Advantages of MVC:

(1) low coupling. Coupling is the degree of association between module codes. Using the MVC Framework, the View layer and the Model layer can be well separated, which achieves the goal of decoupling, so the coupling is low, reduce the interaction between module codes.

(2) good scalability. Due to low coupling, you can add more code to reduce the number of code changes and reduce the bug occurrence rate.

(3) clearly divided responsibilities of the module. It is mainly divided into three modules: M, V, and C, which facilitates code maintenance.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.