Android Learning file storage

Source: Internet
Author: User

A small case of file storage was done today, and this is a way to solidify the unit testing and MVC design patterns in Android.

. The ANDROIDMVC mode is as follows

Step 1: Layout editing:

The layout page and code are as follows:

<Button Android:id= "@+id/btnsave"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:layout_below= "@+id/etcontent"Android:layout_centerhorizontal= "true"Android:layout_margintop= "39DP"Android:text= "@string/btn_tip_save"/> <EditText Android:id= "@+id/etcontent"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:layout_alignparenttop= "true"Android:layout_centerhorizontal= "true"Android:layout_margintop= "74DP"Android:drawableleft= "@drawable/icon"Android:ems= "15"Android:hint= "@string/et_tip_writecontent"Android:minlines= "3" > <!--EMS Length--<requestfocus/> </EditText>

Where:android:ems= "Four" for setting the width of the textview or edittext width to 15 characters

Step 2: Business layer editing:

The code is as follows:

 PackageCom.example.savafile.service;ImportJava.io.BufferedReader;ImportJava.io.BufferedWriter;ImportJava.io.FileInputStream;Importjava.io.FileNotFoundException;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.io.InputStreamReader;ImportJava.io.OutputStreamWriter;ImportAndroid.content.Context;/**For the operation of the page, where the data is saved and read*/ Public classFileservice {Privatecontext Context; PrivateString FileName; /**Initialize context and file name (path)*/     PublicFileservice (Context context, String FileName) { This. Context =context;  This. FileName =FileName; }     Public BooleanSave (String content) {Booleanissavesuccessed =false; BufferedWriter BW=NULL; Try {            //Create an output stream for the context (data flow outside the program)//parameter 1 is the stored file name, Parameter 2 is modeFileOutputStream fos = context.openfileoutput (FileName, context.mode_private);//building a byte output streamOutputStreamWriter writer =NewOutputStreamWriter (FOS);//wrapping a byte output stream as a character output streamBW =NewBufferedWriter (writer);//wrap the character output stream as a cache stream?Bw.write (content);//the difference between write and OutputStreamissavesuccessed =true; } Catch(FileNotFoundException e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }finally{            Try {                //why doesn't write and Fos shut down?                if(BW! =NULL) {bw.close (); }            } Catch(IOException e) {e.printstacktrace (); }        }        returnissavesuccessed; }     Publicstring Read () {string line; StringBuilder SB=NewStringBuilder ();//What's the role?BufferedReader br =NULL; Try{FileInputStream fis= Context.openfileinput (FileName);//get the input stream through the Openfileinput (path) method in the contextBR =NewBufferedReader (NewInputStreamReader (FIS));  while(line = Br.readline ())! =NULL) {sb.append (line);//s +=line; consistent, but can cause a lot of memory waste            }        } Catch(IOException e) {//Br.readline () exception blockE.printstacktrace (); }                returnsb.tostring (); }}

Here I am using the I/O stream in Java, that is, the input and output stream, the small series search the corresponding data as follows:

You can learn through books, web and other materials.

--------------------------------------------------------------------------------------

It is important to note that after editing the business layer, the method in the business layer needs to be unit tested to ensure its correctness. Make sure that the method in the business layer is correct, then edit the control layer (Activity), then, if the error occurs, you can determine that the fault is not in the business layer, to the control layer or the model layer for troubleshooting .

The unit test steps are as follows:

① Configuring the environment required for unit testing in the Androidmanifest.xml file

In the graph, the content within the red line is the desired

② writes the appropriate test method by inheriting the Androidtestcase parent class provided by Android

The code is as follows:

 Packagecom.example.savafile.serviceTest;ImportCom.example.savafile.service.FileService;Importandroid.test.AndroidTestCase;/**Unit Test*/ Public classServicetestextendsAndroidtestcase {/**test the Save method in Fileservice*/     Public voidTestsave () {Fileservice Testsave=NewFileservice (GetContext (), "data");//stored as an XML file?Testsave.save ("Hello Test"); }        /**test the Read method in Fileservice*/     Public voidTestread () {Fileservice Testread=NewFileservice (GetContext (), "data");//stored as an XML file?Testread.read (); }}

The method name of the unit test is best named by the method name that test+ needs to test

③ Run Test:

When you open a virtual machine (or a real machine), right-click the outline method in the unit test class and run it as an Android project

Test results:

On success, the Red Flag section shows a green progress bar, which, conversely, is a red progress bar, and the error message of the test method is displayed in the yellow marker area, which is very useful!

Step 3: Control layer editing:

The code is as follows:

 PackageCom.example.savafile;ImportCom.example.savafile.service.FileService;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button;ImportAndroid.widget.EditText;ImportAndroid.widget.Toast;/**Android Development follows the MVC principle M Business layer (Fileservice) V (XML layout) C control Layer (Activity) * Test the business layer, must be unit tested, determine the business layer method without problem, write the control layer*/ Public classMainactivityextendsActivityImplementsOnclicklistener {PrivateButton btnsvae; PrivateEditText etcontent; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);                Setcontentview (R.layout.activity_main);        Initialize ();            ReadText (); }        /**initialize the control and set the appropriate listener*/    Private voidInitialize () {btnsvae=(Button) Findviewbyid (R.id.btnsave); Etcontent=(EditText) Findviewbyid (r.id.etcontent); Btnsvae.setonclicklistener ( This); }        /**read the data stored before*/    Private voidReadText () {String data=Fileservice.read (); if(data!=NULL) {etcontent.settext (data); }} fileservice Fileservice=NewFileservice (mainactivity. This, "Data.txt"); /**Listener Method*/@Override Public voidOnClick (View v) {Switch(V.getid ()) { CaseR.id.btnsave:if(Fileservice.save (Etcontent.gettext (). toString ())) {//whether the save was successfulToast.maketext (mainactivity. This, "Congratulations, save your success!", Toast.length_short). Show (); }Else{toast.maketext (mainactivity). This, "Good pity, save failed!", Toast.length_short). Show (); }             Break; }    }}

Here, even if the editor is finished. Thank you.

Android Learning file storage

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.