Data storage in Android 11 (1)

Source: Internet
Author: User

Data storage in Android mainly includes the following methods:

1. Use SharedPreferences: This storage method is mainly used for applications to save a small amount of data, and the data format is very simple.

2. File Storage: This allows us to easily access files in mobile phone memory (mobile phone memory card or user's SD card)

3. SQLite Database: the Android system integrates a lightweight database.

4. Network: save data on the network platform for storage

I will guide you through these steps:

1. When using SharedPreferences, we need to get two important objects: SharedPreferences and SharedPreferences. Editor. Then we can add or retrieve the corresponding data:

1) add data:

// Get the SharedPreferences instance, indicating that the SharedPreferences can only be read and written by this application // MODE_WORLD_READABLE: can only be read by other programs, but cannot write // MODE_WORLD_WRITEABLE: other applications can read and write SharedPreferences preferences = getSharedPreferences ("myFile", MODE_PRIVATE); SharedPreferences. editor editor = preferences. edit (); // get SharedPreferences. editor object SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd hh: mm: ss"); // store the specified key data editor to SharedPreferences through the editor. putString ("time", sdf. format (new Date (); editor. putInt ("random", (int) (Math. random () * 100); editor. commit (); // submit the stored data

2) retrieve the corresponding data:

SharedPreferences preferences = getSharedPreferences ("myFile", MODE_PRIVATE); // gets the value of the specified key. If no value exists, the default value String time = preferences is returned. getString ("time", null); int random = preferences. getInt ("random", 0); String result = time = null? "You have not written data": "write time:" + time + "\ n:" + random; Toast. makeText (SharedPreferencesTestActivity. this, results, 5000 ). show ();

The above code has comments. I believe you can understand it easily!

2. File writing and reading

In android, we can write and read files in the memory card of our mobile phone or the SD card inserted by the user.

In essence, it is to create an input and output stream, and then read and write data in it, which is the IO operation in java!

1) store data in the built-in storage space of our mobile phone <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHByZSBjbGFzcz0 = "brush: java;">/*** this method saves data in the built-in storage space of our mobile phone, mainly by calling Context. the openFileOutput (fileName, MODE) method can obtain the corresponding output stream * fileName: the commonly used separator ("/") cannot be used. For example: aaa/test.txt. we can only store the files saved by test.txt * in the/data/package name/files/directory, for example,/data/com. xin. activity/files/test.txt * MODE: There are the following types: * context. MODE_PRIVATE: private data of the current application. Other applications cannot read or write access. Otherwise, the permission denni error may occur. * If the file already exists, the re-written file will overwrite the data in the previous file; * context. MODE_APPEND: private data in the current application. Other applications cannot read or write access. Otherwise, the permission denni error may occur. * If the file already exists, the re-written data will be appended to the data of the source file; * context. MODE_WORLD_READABLE: Other applications can read the file and cannot write the file. Otherwise, the permission denni error may occur. * context. MODE_WORLD_WRITEABLE: Other applications can perform write operations on the file and cannot perform read operations. Otherwise, the permission denni error may occur; * To enable other applications to read and write files, you can use * context. MODE_WORLD_READABLE + context. MODE_WORLD_WRITEABLE: input the parameter *. The saved file contains Chinese characters and will not contain garbled characters. * You can use window --> android --> file explorer to view the system file * @ param fileName * @ param fileContent. * @ throws Exception */public void save (String fileName, string fileContent) throws Exception {FileOutputStream fos = context. openFileOutput (fileName, context. MODE_WORLD_WRITEABLE); fos. write (fileContent. getBytes ());}

2) read data from the built-in storage space of the mobile phone

/*** Read data from the built-in bucket of the mobile phone, mainly by calling context. openFileInput (fileName) method, input parameter file name * @ return */public String read (String fileName) throws Exception {FileInputStream FCM = context. openFileInput (fileName); byte [] buffer = new byte [1024]; int len = 0; // save in memory, you can also output ByteArrayOutputStream baos = new ByteArrayOutputStream (); // StringBuilder sb = new StringBuilder (); while (len = FCM. read (buffer ))! =-1) {baos. write (buffer, 0, len); // sb. append (new String (buffer, 0, len);} byte [] B = baos. toByteArray (); return new String (B); // return sb. toString ();}

3) Save the file to the SD card of the mobile phone's external storage device.

/*** Save the file to the SD card of the external storage device of the mobile phone * access the hardware device. We need to configure the corresponding permissions to access the SD card in AndroidMainifest. xml *
     
     
     
 Note that the root directory of the external storage device may be different because the android system version is different, for example, Version 2.1/sdcard /, in version 2.2, we cannot write/mnt/sdcard/to death and use Environment. getExternalStorageDirectory () can get different versions of the root directory, so if the file already exists in this way, the content will overwrite * @ param fileName * @ param fileContent * @ throws Exception */public void saveToSDCard (String fileName, String fileContent) throws Exception {// Environment. getExternalStorageDirectory () --->/sdcardFile file = new File (Environment. getExternalStorageDirectory (), fileName); FileOutputStream fos = new FileOutputStream (file); fos. write (fileContent. getBytes ());}

4) read the content in the SD card file

/*** Read the content in the SD card file * @ param fileName * @ return * @ throws Exception */public String readSDCard (String fileName) throws Exception {File file = new File (Environment. getExternalStorageDirectory () + File. separator + fileName); FileInputStream FCM = new FileInputStream (file); byte [] buffer = new byte [1024]; int len = 0; ByteArrayOutputStream baos = new ByteArrayOutputStream (); while (len = FCM. read (buffer ))! =-1) {baos. write (buffer, 0, len);} byte [] B = baos. toByteArray (); return new String (B );}


All the above Code has comments, which are easy to understand! Reading and Writing files from the memory card provided by the mobile phone is mainly used to obtain the corresponding byte input stream and byte output stream from the openFileInput and openFileOutput classes provided by the current Context provided by android, the operation of the files on the SD card is mainly to obtain the path of the files in the SD card. We use Environment. getExternalStorageDirectory () to get its root directory, and then perform corresponding IO stream operations on the files in it. Is the file storage so easy!

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.