Android data store-file operations

Source: Internet
Author: User
Tags save file

First, the preparation of knowledge

MVC Design Patterns in 1.Android

MVC (Model-view-controller): M refers to the logical model, v refers to the view model, and C is the controller. A logical model can be used for a variety of view models, such as a batch of statistical data you can use a histogram, pie chart to represent. A view model can also be used for multiple logical models. The purpose of using MVC is to separate the implementation code for M and v so that the same program can use different representations, whereas C exists to ensure the synchronization of M and V, and once m changes, V should be updated synchronously, which is exactly the same as the Observer pattern in design mode.

MVC benefits: From the user's point of view, users can choose their own appropriate way to browse the data according to their own needs. For example, for an online document, you can choose to read it as an HTML page, or you can choose to read it in PDF mode. From the developer's point of view, MVC separates the logic layer of the application from the interface, and the biggest benefit is that the interface designer can directly participate in the interface development, the programmer can focus on the logic layer. Rather than as before, designers put all the material in the hands of developers, who implement the interface. In the Eclipes tool, the development of Android in a more simple way, designers in the DroidDraw design interface, in XML storage, in the Eclipes directly open to see the designer interface.

The interface part of Android also uses the currently popular MVC framework, in Android:

1) View layer: The general use of XML file interface description, when used can be very convenient to introduce. Of course, how you learn more about Android, you can think of Android can also use javascript+html and other ways as the view layer, of course, there is a need for Java and JavaScript communication between, fortunately, Android provides a very convenient communication implementation between them.

2) control layer (Controller): The task of Android control layer usually falls on the shoulders of many acitvity, this phrase also implies do not write code in acitivity, to through activity delivery model business Logic layer processing, Another reason for this is that the response time of Acitivity in Android is 5s, and if time-consuming operations are put here, the program is easily recycled.

3) Model: the operation of the database, the operation of the network, etc. should be processed in the model, of course, business calculations and other operations must be placed in the layer. is the binary data in the application.

Data binding in the Android SDK also uses a similar approach to the MVC framework to display the data. Data binding is achieved by encapsulating the data in the control layer as required by the view model (that is, the adapter in the Android SDK) to be displayed directly on the view model. For example, the listactivity of all the data in the cursor, the view layer is a ListView, the data is encapsulated as ListAdapter, and passed to the ListView, the data is in the ListView reality.

File operations in 2.Android

the file operation in Android, similar to Java, because it is Java-based, so Java file operation ideas for Android, file operations using a concept of flow, similar to water and pool

The output stream is like a water injection in a pool, and the input stream is like an external conveyance

Data-----Output----->>> file (output stream) in the interface

Data in the file-----input----->>> Interface (input stream)

Here are some of the Java concepts for streaming (from http://blog.csdn.net/liuxiaogangqq/article/details/25892667 ):

2.1 Data Flow

A set of ordered, byte data sequences with start and end points. Include input stream and output stream

2.2 Inputs stream (input stream)

The program reads the data source from the input stream. The data source includes the outside world (keyboard, file, network ...), which is the communication channel in which the data source is read into the program

2.3 Outputs stream (output stream)

The program writes data to the output stream. Output data from the program to the outside world (monitor, printer, file, network ...) ) of the communication channel

Second, the Android program case-the implementation of file read and write operations

Let's take a look at the effect demo:

1. Layout aspect only one textview, one edittext, two button---view layer

2. Writing the model layer, i.e. fileservice                                                                    --model layer

Package Cn.edu.bzu.service;import Android.content.context;import Java.io.bufferedreader;import Java.io.bufferedwriter;import Java.io.fileinputstream;import Java.io.filenotfoundexception;import Java.io.fileoutputstream;import Java.io.ioexception;import Java.io.inputstreamreader;import java.io.outputstreamwriter;/** * MVC design mode * M:model V:view c:control * File Operation service class, both file read and write function * Created by monster on 2015/5/2 9. */public class Fileservice {Private context context;//context private String fileName;//File name public Fileservice (context context, String fileName)        {//constructor method for incoming context This.context = context;    This.filename = FileName; /** * Save File * Idea: Create file output stream-->> Create file reader/writer-->> Create buffer-->> write operation */public boolean saveFile (Strin        G content) {BufferedWriter bw=null;//Buffer declaration Boolean Issavesuccess=false; try {fileoutputstream fileoutputstream=context.openfileoutput (filename,context. Mode_private); Create an output stream OutputstreaMwriter outputstreamwriter=new OutputStreamWriter (FileOutputStream); Create Reader Bw=new BufferedWriter (outputstreamwriter);            Creates a buffered character output stream Bw.write (content) using the default size output buffer;        Issavesuccess=true;        } catch (FileNotFoundException e) {e.printstacktrace ();        } catch (IOException e) {e.printstacktrace ();                }finally {if (bw! = NULL) {try {bw.close ();                } catch (IOException e) {e.printstacktrace ();    }}} return issavesuccess; /** * Read file * Create input stream--Create reader-->> create buffer-->> Read Data */public String read () {Bufferedrea        Der Br=null;        String Line; StringBuffer sb=new StringBuffer ();  Used to add data try {FileInputStream fileinputstream=context.openfileinput (fileName); Create a file stream InputStreamReader inputstreamreader=new inputstreamreader (FileInputStream);Create Reader Br=new BufferedReader (inputstreamreader);            while ((Line=br.readline ())!=null) {sb.append (line);        }} catch (FileNotFoundException e) {e.printstacktrace ();        } catch (IOException e) {e.printstacktrace ();                }finally {if (br!=null) {try {br.close ();                } catch (IOException e) {e.printstacktrace ();    }}} return Sb.tostring (); }}

This part of the code is the model layer, so for better use, we'll write a test class:

Fileservicetest.java:

Package Cn.edu.bzu.test;import Android.test.androidtestcase;import cn.edu.bzu.service.fileservice;/** * File Operation Test class, Tested with Android JUnit Test * @author Monster * date:2015-05-30 */public class Fileservietest extends Androidtestcase {    p ublic void Testsave () {        fileservice fileservice=new fileservice (GetContext (), "test.txt");        Fileservice.savefile ("Hello World");}    }

Then configure the manifest file:

Then test the Android JUnit test:

Test Result: Success

Write control layer Code--control layer after successful test

Mainactivity.java:

Package Cn.edu.bzu.fileoperate;import Cn.edu.bzu.service.fileservice;import Android.app.activity;import Android.os.bundle;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.Button; Import Android.widget.edittext;import android.widget.toast;/** * Store data and read data by clicking the button * @author monster * Using MVC design pattern * date:2    015-05-30 */public class Mainactivity extends Activity implements onclicklistener{private EditText edt_content;    Private Button Btn_save,btn_read;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);    Initview ();        } private void Initview () {edt_content= (EditText) Findviewbyid (r.id.content);        Btn_save= (Button) Findviewbyid (R.id.btn_save);                Btn_read= (Button) Findviewbyid (R.id.btn_read);        Btn_save.setonclicklistener (this);    Btn_read.setonclicklistener (this); } @Override public void OncliCK (View v) {switch (V.getid ()) {case r.id.btn_save:string content=edt_content.gettext (). toString (); Get the value if (content!=null) {fileservice fs=new fileservice (mainactivity.this, "Information.txt");                /By constructing a method to pass in the context and file name Boolean issuccessed=fs.savefile (content);                if (issuccessed) {Toast.maketext (mainactivity.this, "Data saved successfully", Toast.length_short). Show ();            }}else{Toast.maketext (mainactivity.this, "Please enter what you want to save", Toast.length_short). Show ();        } break;            Case R.id.btn_read:fileservice fs=new Fileservice (mainactivity.this, "Information.txt");  String Info=fs.read (); Read the data if (info!=null) {edt_content.settext (info);//Set the value to EditText toast.maketext (            Mainactivity.this, "Read data Success", Toast.length_short). Show (); }else{Toast.maketext (mainactivity.this, "Error reading data", TOast.            Length_short). Show ();        } break; }            }}

----->>> OK, done

Iii. Summary

In this case, we need to master:

1.Android MVC design Pattern

The basic idea of 2.Android file operation

3.JAVA exception handling mechanism

4.JUnit for unit Testing

Iv. Source code:

Https://github.com/monsterLin/FileOperate.git

Android data store-file operations

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.