Android Data storage

Source: Internet
Author: User
Tags gettext

Data storage is important in Android development, as a project is bound to use data storage, such as game or application configuration, game archiving, application usage, etc. This article mainly writes the local file storage, the next chapter will introduce the database related content.
The first thing to say about Android storage structure, storage space
Android devices have two storage space:

Internal storage space

RAM memory: Running memory, equivalent to the computer's memory
ROM Memory: Storage memory, equivalent to the computer's hard disk

External storage space

SD card: Equivalent to the computer's mobile hard disk, optional
Many of today's mobile phones do not support SD cards, but there is external storage space. For example, mobile phone memory 32G, in fact, refers to the external space. And how big is the ROM. Mobile phone manufacturers don't usually tell you. For ordinary users, it is not known, and we programmers can get it.
Our read-write files can be stored internally or externally.

1. write files in internal storage

Eg. save user name password, tick remember user name, first login save username to local

layout file is two exittext, a checkbox and a button. (This checkbox should be added with a android:layout_centervertical= "true" to center vertically in the parent element)

The steps to store a file in Java are:
File File = new file (" D:/info.txt ");
FileOutputStream fos = new FileOutputStream (file);
Fos.write (buffer); The
is as simple as Android: first we look at the Android storage directory structure File explorer (not found, can be found here window--show view--other--file Explorer)
Our application data is stored under the path "data-data-Project package name" of the internal storage space. So we changed the upper statement to the complete notation:
String name = Et_name.gettext (). toString ();
String pass = Et_pass.gettext (0.toString ();
CheckBox cb = (checkbox) Findviewbyid (R.ID.CB);
if (cb.ischecked ()) {
File File = new file ("Data/data/com.live.rwinrom/info.txt");
FileOutputStream fos = new FileOutputStream (file);
try{
Fos.write ((name + "# #" + Pass). GetBytes ());//# #是为了拆分用户名和密码. This is not done in the formal development of
Fos.close ();//Off-stream.
}catch (Exception e) {
E.printstacktrace ();
}
When we click the login button to execute the top code, we can generate the Info.txt file in the internal storage space.

2. Read the file in the internal storage

  • Detect if the file exists before reading the data
    if (File.exists ())
  • Read the saved data, also directly open the file input stream read
    File File = new file ("Data/data/com.live.rwinrom/info.txt");
    FileInputStream fis = new FileInputStream (file);
    Convert bytes into character streams
    BufferedReader br = new BufferedReader (new InputStreamReader (FIS));
    String text = Br.readline ();
    String[] s = Text.split ("# #");
  • After reading to the data, echo back to the input box
    Et_name.settext (S[0]);
    Et_pass.settext (S[1]);
  • The app can only create files in its own package and can't go to other people's homes. Permissions
    3. Use the path API to get the internal storage path
    Because the "data/data/com.live.rwinrom/info.txt" path in the previous section is fixed, it is unusual to write a single character, and it is inefficient to spell a long string, and sometimes it is best to call it directly with some database APIs when making database statements. So we can do it the following way.
  • Getfilesdir () The path to the resulting file object is Data/data/com.live.rwinrom/files
    File File = new file (Getfilesdir (), "info.txt");
    • Files stored in this path, as long as you do not delete, it has been in
  • Getcachedir () The path to the resulting file object is Data/data/com.live.rwinrom/cache

    • Files stored under this path may be deleted when memory is low
      • For example, we open the circle of friends, there are a lot of pictures Ah, the first time to open slowly, the second time opened. These are the caches that exist.
      • Google said that in the memory of the system, the cache file may be deleted, it may not be deleted, it is recommended that we build a valve, such as to achieve 1MB deletion.
  • The System Management application interface clears the cache, clears the contents of the cache folder, clears the data, and clears the entire package.

    4. Read and write files on external storage

Path to SD card
    • SD card path prior to sdcard:2.3
    • SD card path prior to mnt/sdcard:4.3
    • SD card path after storage/sdcard:4.3

    • The simplest way to open an SD card

      File file = new File("sdcard/info.txt");//谷歌为了兼容低版本,在存储空间中建了一个sdcard文件快捷方式指向storage/sdcard
    • Write SD card requires permission

      <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    • Read SD card, do not need permission before 4.0, 4.0 can be set to need

      <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    • Use API to get the real path of SD card, some phone brands will change the path of SD card

      Environment.getExternalStorageDirectory()
    • Determine if the SD card is ready

      if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))

5. File access rights

    • In Android, each app is a standalone user
    • Drwxrwxrwx
    • 1th bit: D represents a folder,-represents a file
    • 第2-4位: rwx, which indicates the owner user (owner) of this file has permission to the file
      • R: Read
      • W: Write
      • X: Execute
    • 第5-7位: Rwx, which represents the permissions of the user (grouper) in the same group as the file owner user
    • 第8-10位: rwx, which indicates that the user (other) of another user group has permission to the file
Four modes of Openfileoutput
    • mode_private:-rw-rw--
    • mode_append:-rw-rw--
    • mode_world_writeable:-rw-rw–w-
    • mode_world_readable:-rw-rw-r–

6. Use Sharedpreference to store account password

    • Write data to Sharedpreference.

      //拿到一个SharedPreference对象SharedPreferences sp = getSharedPreferences("config", MODE_PRIVATE);//拿到编辑器Editor ed = sp.edit();//写数据ed.putString("name", name);ed.commit();
    • Fetch data from Sharedpreference.

      SharedPreferences sp = getSharedPreferences("config", MODE_PRIVATE);//从SharedPreference里取数据String name = sp.getBoolean("name", "");

7. Generating an XML file

The above few storage methods are not enough to meet our needs, such as we want to back up SMS. Each text message, with a minimum of four data: Address sender phone number, body text message content, date time, type information types (Received or issued).
* First build a Message object
public class Message {
Private String body;
Private String date;
Private String address;
Private String type;
Public String GetBody () {
return body;
}
public void Setbody (String body) {
This.body = body;
}
Public String getDate () {
return date;
}
public void SetDate (String date) {
This.date = date;
}
Public String getaddress () {
return address;
}
public void setaddress (String address) {
this.address = address;
}
Public String GetType () {
return type;
}
public void SetType (String type) {
This.type = type;
}
Public Message (string body, string date, string address, String type) {
Super ();
This.body = body;
This.date = date;
this.address = address;
This.type = type;
}

}

    • Create a few virtual SMS objects, exist in list, and back up data are usually backed up to SD card, using StringBuffer stitching string, the entire XML file all nodes append into SB object
      public class Mainactivity extends Activity {
      List smslist;
      @Override
      protected void OnCreate (Bundle savedinstancestate) {
      Super.oncreate (savedinstancestate);
      Setcontentview (R.layout.activity_main);

      //虚拟10条短信smsList = new ArrayList<Message>();for(int i = 0; i < 10; i++){    Message sms = new Message("李伟好棒" + i, System.currentTimeMillis() + "", "138"+i+i, "1");    smsList.add(sms);}

      }
      public void Click (View v) {
      In memory, the format of the XML backup SMS is stitched up
      StringBuffer sb = new StringBuffer ();
      Sb.append ("

Get the XML file
    InputStream is = getClassLoader().getResourceAsStream("weather.xml");
Get the pull parser.
    XmlPullParser xp = Xml.newPullParser();
Start parsing
  • Get the event type of the current node where the pointer is located

    int type = xp.getEventType();
  • There are five main types of events

    • Event types for Start_document:xml headers
    • Type of event End_document:xml tail
    • Start_tag: Event type of the start node
    • End_tag: Event type for end node
    • Text: The event type of the literal node
  • If the obtained event type is not end_document, then the parsing is not complete, and if it is, the parsing is complete and the while loop ends

    while(type != XmlPullParser.END_DOCUMENT)
  • When we resolve to different nodes, we need to do different things, so we can judge the name of the current node.

    • When parsing to the start node of weather, the new list
    • When resolving to the start node of city, the city object is created and the object is created to make it easier to save the text that will be parsed
    • When parsing to the name start node, gets the text content of the next node, same as temp, PM

      case XmlPullParser.START_TAG://获取当前节点的名字    if("weather".equals(xp.getName())){        citys = new ArrayList<City>();    }    else if("city".equals(xp.getName())){        city = new City();    }    else if("name".equals(xp.getName())){        //获取当前节点的下一个节点的文本        String name = xp.nextText();        city.setName(name);    }    else if("temp".equals(xp.getName())){        String temp = xp.nextText();        city.setTemp(temp);    }    else if("pm".equals(xp.getName())){        String pm = xp.nextText();        city.setPm(pm);    }    break;
  • When resolving to the end node of city, it shows that the city's three child nodes have all been parsed, adding the city object to the list

    case XmlPullParser.END_TAG:    if("city".equals(xp.getName())){            citys.add(city);    }

End-of-hair benefits:

Shortcut keys CTRL + 1, set convert local variable to field, local variables are set directly to global variables.

Android Data storage

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.