Small white learn Android MVP and Sharedpreferences storage Jsonarray

Source: Internet
Author: User

it used to be MVC to develop Android apps, but it felt that the frequent interaction of M and V in activity made the code bloated and the number of lines of code

It's easy to reach thousands of lines. Not only that, the use of MVC makes the code readable and maintainable is very low scalability, some small functions of the increase,

Deleting, modifying, and querying are very difficult, especially when the code is transferred to others for maintenance.

The advent of the MVP model solves these problems well, and you'll find that with the MVP model, you don't want to use the MVC pattern anymore. Code bundle for MVP mode

Frame




M-layer interface writes the non-implemented logical method, implements all the logical methods with the implementation class of the M layer, and the V-layer interface writes to the side of the interface interaction

method, using the V-Layer implementation class, activity or fragment, to implement all interface interaction methods; The P-layer class is constructed to realize the groove of M and V.

Communication and interaction, p is actually the identity of the intermediary. This makes the M and V completely separate and perform their duties.

Sharedpreferences store data requires Sharedpreferences object and editor object, editor object stores data,

The Sharedpreferences object reads data.

Program Run effect









The code is as follows:

1. Interface Layout Activity_main:

<span style= "FONT-SIZE:18PX;" ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Android:orien        tation= "vertical" > <button android:id= "@+id/btn_jsonarray" android:layout_width= "Match_parent"        android:layout_height= "0DP" android:layout_weight= "1" android:text= "Generate Jsonarray"/> <textview        Android:id= "@+id/tv_jsonarraycontent" android:layout_width= "match_parent" android:layout_height= "0DP" android:layout_weight= "4" android:gravity= "center" android:text= "@string/hello_world" Android:         Textsize= "20sp"/> <button android:id= "@+id/btn_jsonarrayparse" android:layout_width= "Match_parent" android:layout_height= "0DP" android:layout_weight= "1" android:text= "Parse Jsonarray"/> <textvi EW ANdroid:id= "@+id/tv_jsonarrayparsecontent" android:layout_width= "match_parent" android:layout_height= "0DP" android:layout_weight= "4" android:gravity= "center" android:text= "@string/hello_world" Android:te Xtsize= "20SP"/></linearlayout></span>




2. Main interface Model interface Mainmodelinterface:


<span style= "FONT-SIZE:18PX;" >package com.msd.spsavejsonarray.model.interfaces;/* * Main interface Model Interface */public interface Mainmodelinterface {/* * Generate Jsonarray */string generatespsavejsonarray ();/* Parse Jsonarray */string parsespsavejsonarray (String jsonArrayContent );} </span>

3. The implementation class Mainmodelclass of the main interface model interface:


<span style= "FONT-SIZE:18PX;" >package Com.msd.spsavejsonarray.model.classes;import Org.json.jsonarray;import Org.json.JSONException;import Org.json.jsonobject;import com.msd.spsavejsonarray.model.interfaces.mainmodelinterface;/* * Implementation class for interface of main interface model */public Class Mainmodelclass implements Mainmodelinterface {/* * (NON-JAVADOC) Generate Jsonarray Implementation * * @see Com.msd.spsavejsonarray.mo del.interfaces.mainmodelinterface# * Generatespsavejsonarray () */@Overridepublic String Generatespsavejsonarray () { Jsonarray Jsonarray = new Jsonarray (); Jsonobject jsonobject;for (int i = 0; i < 5; i++) {jsonobject = new jsonobject (); try {jsonobject.put ("id", "id_" + i); j Sonobject.put ("name", "name_" + i); Jsonarray.put (jsonobject);} catch (Jsonexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}} return jsonarray.tostring ();} /* * (Non-javadoc) Parse Jsonarray implementation, return String * * @see com.msd.spsavejsonarray.model.interfaces.mainmodelinterface# * Parsespsavejsonarray (java.lang.String) */@Overridepublic StriNg Parsespsavejsonarray (String jsonarraycontent) {StringBuilder StringBuilder = new StringBuilder (); try {Jsonarray Jsonarray = new Jsonarray (jsonarraycontent); Jsonobject jsonobject;for (int i = 0; i < jsonarray.length (); i++) {jsonobject = (jsonobject) jsonarray.get (i); stringBu Ilder.append ("+ i +" entry: "+" id "+ jsonobject.getstring (" id ") +" name "+ jsonobject.getstring (" name ") +" \ n ");}} catch (Jsonexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} return stringbuilder.tostring ();}} </span>



4. Main interface View interface Mainviewinterface:

<span style= "FONT-SIZE:18PX;" >package com.msd.spsavejsonarray.view.interfaces;/* * Main Interface View Interface */public interface Mainviewinterface {/* * Displays the generated Jsonarray */void Showgeneratejsonarray (String jsonarraystring); */* Displays the parsed Jsonarray */void Showparsejsonarray ( String jsonarrayparsestring);} </span>

5. Main interface View interface implementation Class Mainactivity:

<span style= "FONT-SIZE:18PX;" >package Com.msd.spsavejsonarray.view.classes;import Android.app.activity;import Android.content.sharedpreferences;import Android.content.sharedpreferences.editor;import Android.os.Bundle; Import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.textview;import Com.msd.spsavejsonarray.r;import Com.msd.spsavejsonarray.presenter.mainpresenter;import com.msd.spsavejsonarray.view.interfaces.mainviewinterface;/* * Main interface View interface implementation Classes */public class Mainactivity extends Activity implements Onclicklistener,mainviewinterface {private sharedpreferences sharedpreferences;// Sharedpreferences Object private Static editor editor;//Editor object private String spname = "Spsavejsonarray";// File name stored by SP private Mainpresenter mainpresenter;//main Interface presenter Object private TextView tv_jsonarraycontent;// Displays the textviewprivate of the generated Jsonarray TextView tv_jsonarrayparsecontent;//shows Jsonarray void for parsing textview@overrideprotected OnCreate (Bundle savedinstancestate) {super.oncreatE (savedinstancestate); Setcontentview (r.layout.activity_main); mainpresenter = new Mainpresenter (this); Sharedpreferences = Getsharedpreferences (spname, mode_private);//private Mode editor = Sharedpreferences.edit (); tv_ Jsonarraycontent = (TextView) Findviewbyid (r.id.tv_jsonarraycontent); tv_jsonarrayparsecontent = (TextView) Findviewbyid (r.id.tv_jsonarrayparsecontent); Findviewbyid (R.id.btn_jsonarray). Setonclicklistener (this); Findviewbyid (R.id.btn_jsonarrayparse). Setonclicklistener (this);} /* * If you reference presenter in activity to perform time-consuming operations and the activity is destroyed, the presenter object will always hold the activity object, * potentially causing a memory leak, so perform an insurance operation, in OnDestroy () Clears the Activity's reference to the presenter object, * or empties the Prensenter object's reference to the Acitvity object (non-javadoc) * * @see Android.app.activity#ondestroy () * /@Overrideprotected void OnDestroy () {//TODO auto-generated method Stubsuper.ondestroy (); mainpresenter = null;} /* * Click event * * @see Android.view.view.onclicklistener#onclick (android.view.View) */@Overridepublic void OnClick (view view {switch (View.getid ()) {case r.id.btn_jsonarray://generated JSONarraymainpresenter.generatespsavejsonarray (); Break;case r.id.btn_jsonarrayparse:// Parse Jsonarraymainpresenter.parsespsavejsonarray (); break;default:break;}} /* * Show generated Jsonarray (non-javadoc) * * @see * Com.msd.spsavejsonarray.view.mainviewinterface#showgeneratejsonarray (* java.lang.String) */@Overridepublic void Showgeneratejsonarray (String jsonarraystring) {editor.putstring (spname, jsonarraystring). commit ();//Store the generated Jsonarray tv_jsonarraycontent.settext (jsonarraystring);//Tv_ Jsonarrayparsecontent.settext (Sharedpreferences.getstring (spname,//"[]"));//Get generated jsonarray}/* from SP * Show parsed Jsonarray (non-javadoc) * * @see * Com.msd.spsavejsonarray.view.mainviewinterface#showparsejsonarray (java *. lang) . String) */@Overridepublic void Showparsejsonarray (String jsonarrayparsestring) {Tv_jsonarrayparsecontent.settext ( jsonarrayparsestring);}} </span>

6. Main interface Presenter,mainpresenter:

<span style= "font-size:18px;" >package Com.msd.spsavejsonarray.presenter;import Com.msd.spsavejsonarray.model.classes.mainmodelclass;import Com.msd.spsavejsonarray.model.interfaces.mainmodelinterface;import com.msd.spsavejsonarray.view.interfaces.mainviewinterface;/* * Main Interface presenter */public class Mainpresenter {private Mainmodelinterface mainmodelinterface;//main interface model interface implementation class object private Mainviewinterface mainviewinterface;// The main interface view interface implements the object of the class, i.e. the mainactivity/* * Construction method implements the interaction between M and V */public mainpresenter (mainviewinterface mainviewinterface) { Mainmodelinterface = new Mainmodelclass (); this.mainviewinterface = Mainviewinterface;} /* * Generate Jsonarray */public void Generatespsavejsonarray () {Mainviewinterface.showgeneratejsonarray ( Mainmodelinterface.generatespsavejsonarray ());} /* Parse Jsonarray */public void Parsespsavejsonarray () {Mainviewinterface.showparsejsonarray ( Mainmodelinterface.parsespsavejsonarray (Mainmodelinterface.generatespsavejsonarray ()));}} </span> 

Summary: The above code looks very dramatic, but to really do the project, if the interface is more complex, interface interaction elements, the advantages of MVP is fully displayed, activity in the thousands of lines of code becomes clear, very concise, very easy to maintain and modify.

Code Download:

Click to open link








Small white learn Android MVP and Sharedpreferences storage Jsonarray

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.