Saving and reading Android learning notes

Source: Internet
Author: User

Development Environment:

Win XP + eclipse-jee-helios (version 3.6) + ADT (version 10.0.1) + Android SDK (version 10 );

Test environment for simulators and real machines: Android2.2


In many applications, data needs to be stored for further access. Android provides the following five methods for data storage:

  • File(I/O Technology in Java is used)

  • SharedPreferences (parameter)

  • SQLite Database

  • Content provider)

  • Network


First, let's take a look.FileData Storage Methods

1. the application interface layout is as follows. When you click the "save" button, you can save your input content as a file.

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/10043V919-0.png "title =" dc.png "/>

Note: files can be stored in two locations on the mobile phone. One is the storage space provided by the mobile phone (generally, this capacity is relatively small), and the other is the external storage device (SDCard, generally, the capacity is relatively large ).

2. In the string. xml File under the Project File> res-> values directory, define the strings used in the layout. The Code is as follows:

<? Xml version = "1.0" encoding = "UTF-8"?> <Resources> <string name = "hello"> Hello World, MainActivity! </String> <string name = "app_name"> file operation </string> <string name = "filename"> file name </string> <string name = "filecontent"> file content </string> <string name = "button"> saved </string> <string name = "success"> saved </string> <string name = "fail"> failed to save </string> </resources>

3. Implement the preceding layout in the main. xml File under the Project File> res> layout directory. The Code is as follows:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    >    <TextView        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="@string/filename"    />     <EditText        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:id="@+id/filename"     />     <TextView        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="@string/filecontent"      />     <EditText        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:minLines="3"        android:id="@+id/filecontent"     />     <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/button"        android:id="@+id/button"     /></LinearLayout>

4. Add a click event for the "save" button

Idea: Find the button, listen to the click event, and add the click event processing object.

  • Add the following code to the onCreate () method of the MainActivity class:

Button button = (Button)this.findViewById(R.id.button);button.setOnClickListener(new ButtonOnClickListener());

Add the ButtonOnClickListener class to the MainActivity class:

Private final class ButtonOnClickListener implements View. onClickListener {@ Override public void onClick (View v) {EditText filenameText = (EditText) findViewById (R. id. filename); EditText contentText = (EditText) findViewById (R. id. filecontent); String filename = filenameText. getText (). toString (); String content = contentText. getText (). toString (); FileService service = new FileService (getApplicationContext (); // The parameter is to obtain the context object try {service. save (filename, content); Toast. makeText (getApplication (), R. string. success, 1 ). show ();} catch (Exception e) {Toast. makeText (getApplication (), R. string. fail, 1 ). show (); e. printStackTrace ();}}}
  • In the above Code

service.save(filename,content);

Is the method for saving files. Create a FileService class in the cn. hao. service package to save and read files in this class. The Code is as follows:

Public class FileService {private Context context; // context object provided by Android // assign public FileService (Context context) {super (); this. context = context;}/*** save file * @ param filename file name * @ param content File content */public void save (String filename, String content) throws Exception {// IO Technology in java to save the file // get the output stream object of the file FileOutputStream outStream = context. openFileOutput (filename, Context. MODE_PRIVATE );// Filename cannot be written to a file with a path // mode: append, overwrite, and Operation permission for different groups/Context. in the MODE_PRIVATE private operation mode, the created file can only be used for this application. The file created in the private mode // The content written to the file will overwrite the content of the original file, by default, the output stream will be stored in the/data/application package/files directory // write the output stream to the file outStream. write (content. getBytes (); // close the stream outStream after writing the file. close ();}/*** read File Content * @ param filename file name * @ return file content * @ throws Exception */public String read (String filename) throws Exception {// The openFileInput (filename) method defaults // Use the/files directory to read FileInputStream inStream = context. openFileInput (filename); // data stream object output from memory ByteArrayOutputStream outStream = new ByteArrayOutputStream (); // read data from the file, first, read the data in the input stream to a byte array. // there may be a lot of data in the input stream. We should use a loop to implement byte [] buffer = new byte [1024]; // define a byte array int len = 0; // if it does not reach the end of the file, it will always read while (len = inStream. read (buffer ))! =-1) {// obtain the data outStream read each time. write (buffer, 0, len);} byte [] data = outStream. toByteArray (); // data and content. the data of getBytes () is consistent return new String (data );}}
  • Introduce the test. In this case, the class to be created must inherit AndroidTestCase and be stored in AndroidManifest. introduce the Test Library to the xml file. As mentioned in the previous article. hao. the Code is as follows:

Public class FileServiceTest extends AndroidTestCase {// define a TAG for the log to private static final String TAG = "FileServiceTest"; public void testRead () throws Throwable {FileService service = new FileService (this. getContext (); // this. getContext () gets the context object of the current application this. getContext () // the file name should contain the suffix String result = service. read ("Hello.txt"); Log. I (TAG, result );}}
  • Deploy the application to the simulator. The running result is as follows:

    650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/10043SS7-1.png "title =" Your png"/>

  • When you click Save, you can view the file in the data/files directory and export it to the desktop. You can see that the file content is the input content. The effect is as follows:

  • 650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/10043T117-2.png "title =" 22.png"/>

  • Run the test method testRead () and create a new LOG filter to view the content of the file to be read:

    650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131228/10043Q347-3.png "title =" 24.png"/>


This article from the "Flowers bloom" blog, please be sure to keep this source http://020618.blog.51cto.com/6098149/1293664

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.