"Android Zero-single-row development diary"--android data Storage (top)

Source: Internet
Author: User
Tags getmessage readfile

Before explaining the Android data Source component--contentprovider, I felt it was necessary to figure out the Android data structure first.Data and programs are the two core elements of an application, and data storage is always one of the most important topics in application development and the basic functionality that the development platform must provide. Not only on the Android platform, but on other platforms, the storage of data is always an indispensable piece. Android's data storage is built on a Linux file system that leverages the Linux account system to limit application access to data and deploys a secure and flexible data storage solution. Android's file framework, as well as various data storage means, specifically: Android's file system operations, use of settings files, use of databases, use of data source components, and storage of data in the cloud。One, the Android file system
  1. Android System files directory
    directory content
    System Systems directory, placing the core libraries required for Android to run
    data app directory with apps running on Android and their data
    sdcard extended memory card directory to hold shared data
    mnt Records external storage information for Android mounts








  2. Application data storage mechanism for Android
    In Android, third-party apps and their data are stored in the database directory. Where the application installation package will be stored in the /data/app/ directory, the file name of each installation package is as follows: app package names apk, to avoid duplication.
    For example, a package named Com.test.sample, the Application Data directory is /data/data/com.test.sample/. The corresponding database files are stored in the /data/data/com.test.sample/database/ directory, and the settings files are stored in the /data/data/com.test.sample/shared_prefs /, custom app data files are stored under directory /data/data/com.test.sample/files/ , and so on.
    Not only that, Android will also create an account for each app , only through the app's account has the right to run the application's installation package files, read and write the Application Data directory files (except of course, root permission ), This ensures that the application data is no longer available or destroyed by other applications.
  3. Android file operations
    From the application Data directory can be seen, the data file can be divided into two categories, one is placed in the extended memory files, that is, the files in the/sdcard/directory, they can be shared by each application, and the other is placed in the Application Data directory files, they can only be used by individual applications, can not be read and written by other applications.
    (1) The file read and write mode in the extended memory is the same as standard Java file processing.
    We can create a new Fileutil tool class to help us handle the I/O operation of the file, first we first determine the status of the SD card, see if the SD card is available, how much usable capacity, etc. Create a new class of fileutil, add a method
     1//=================get sdcard information=================== 2 public static Boolean issdcardavailable () {3 String status = Environment.getexternalstoragestate (); 4//environment.media_mounted indicates that the SD card is mounted properly 5 if (Status.equals (environment.media_mounted)) {6 ret Urn true; 7} 8 return false; 9}10 One public static long getsdallsizekb () {//SD card location of File path = Environment.getexternalsto Ragedirectory ();//statfs gets all the StatFs SF = new StatFs (Path.getpath ()) in blocks, and 16//Get a single bloc         The size of k BlockSize = Sf.getblocksize (); 18//Gets all data blocks the number of long allblocks = Sf.getblockcount (); 20 Return SD card size return (Allblocks * blockSize)/1024; KB22}23/**25 * Free size for normal APPLICATION26 * @return27 */28 public static long G       ETSDAVALIBLESIZEKB () {File path = environment.getexternalstoragedirectory (); 30  StatFs SF = new StatFs (Path.getpath ()), a long blockSize = Sf.getblocksize (), and a long avaliablesize = SF. Getavailableblocks (); return (Avaliablesize * blockSize)/1024;//KB34}

    Environment.getexternalstoragedirectory () indicates the directory where the extended storage is obtained. (It is recommended to use this method dynamically, because sdcard This directory path is configurable)
    Statfs.getblocksize after API18 to Statfs.getblocksizelong, other similar getblock methods, about StatFs, details can read this blog
    Then join the event in the activity button1

    Case R.id.button1: {            log.d ("TEST", "SDcard?") +fileutil.issdcardavailable ());            LOG.D ("TEST", "Full capacity" + (float) fileutil.getsdallsizekb ()/1024/1024);            LOG.D ("TEST", "Usable capacity" + (float) fileutil.getsdavaliblesizekb ()/1024/1024);            Toast.maketext (This, "status", Toast.length_short). Show ();            break;        }

    The operation results are as follows

    Next we will determine if a folder exists in the SD card and create a folder

    /**     * @param director folder name     * @return     *    /public static Boolean Isfileexist (String director) {        File File = new file (environment.getexternalstoragedirectory ()                + file.separator + director);        return file.exists ();    }    /**     * Create multiple director     * @param path     * @return     *    /public static Boolean CreateFile ( String director) {        if (Isfileexist (director)) {            return true;        } else {            file file = new file (environmen T.getexternalstoragedirectory ()                    + file.separator + director);            if (!file.mkdirs ()) {                return false;            }            return true;        }    }

    Where File.separator is the delimiter, different operating systems, such as Windows is representative of the "/", but under Linux represents "\". So mind using file.separator instead of delimiters. File.mkdirs () indicates that a folder is created and can be accompanied by the creation of a parent directory, while MkDir () does not, the file for details can be viewed in the official documentation, or read this blog post
    Then add a response event to the button2 in the activity

    Case R.id.button2: {            log.d ("TEST", "Example folder exists?") +fileutil.isfileexist ("example"));            LOG.D ("TEST", "Create Forexample folder" +fileutil.createfile ("Forexample"));            Toast.maketext (This, "Isfile", Toast.length_short). Show ();            break;        }  

    After running, you can see

    We will find a new Forexample folder in the SDcard directory of the phone.
    Finally, we will implement the reading and writing of the file.
    Write:

    /** * * @param director * (you don ' t need to begin with * ENVIRONMENT.GETEXTERNALST Oragedirectory () +file.separator) * @param fileName * @param content * @param encoding * (UTF-8.     ..) * @param isappend *: Context.mode_append * @return * */public static File Writetosdcardfile (stri ng directory, string fileName, string content, String encoding, Boolean isappend) {//mobile SD card PA        Th +path file file = null;        OutputStream OS = null;            try {if (!createfile (directory)) {return file; } file = new file (environment.getexternalstoragedirectory () + file.separator + directory + F            Ile.separator + fileName);            OS = new FileOutputStream (file, isappend);            if (Encoding.equals ("")) {Os.write (Content.getbytes ()); } else {Os.write (content.getbytes(encoding));        } os.flush ();        } catch (IOException e) {log.e ("Fileutil", "Writetosdcardfile:" + e.getmessage ());                } finally {try {if (OS! = null) {os.close ();            }} catch (IOException e) {e.printstacktrace ();    }} return file;  }/** * Write data from InputStream to SDcard */public File writetosdcardfrominput (string directory, string        FileName, InputStream Input) {file file = null;        OutputStream OS = null;            try {if (createFile (directory)) {return file; } file = new file (environment.getexternalstoragedirectory () + file.separator + directory + F            Ile.separator + fileName);            OS = new FileOutputStream (file);            byte[] data = new Byte[bufferd];            int length =-1; while (length = Input.reAD (data))! =-1) {os.write (data, 0, length);        }//Clear cache Os.flush ();            } catch (Exception e) {log.e ("Fileutil", "" "+ E.getmessage ());        E.printstacktrace ();            } finally {try {os.close ();            } catch (Exception e) {e.printstacktrace ();    }} return file; }

    As you can see from the above, there are two ways to write, one to write the string directly, and one to write the data stream to a file. Another thing to mention is that the default directory for file is SDcard directory, so you don't have to add SDcard directory paths every time.
    FileOutputStream (file, isappend) two parameters, the left side is a file, and the right is a Boolean value, True, the data will be followed by the original file written, and false is overwritten.
    Read:

    public static string Readfromsdcardfile (String directory,string fileName) {        string res= "";         File file = null;        File = new file (environment.getexternalstoragedirectory ()                + file.separator + directory + file.separator + fileName);        try {            FileInputStream fis = new FileInputStream (file);            int length = fis.available ();            byte [] buffer = new Byte[length];             Fis.read (buffer);
    Converts bytes into string res = encodingutils.getstring (buffer, "UTF-8") in encoded format; Fis.close (); return res; } catch (FileNotFoundException e) { //TODO auto-generated catch block log.d ("TEST", "FileNotFound"); E.printstacktrace (); } catch (Exception e) { log.d ("TEST", "Can not Open File"); E.printstacktrace (); } return null; }

    The encoding is UTF-8 by default, and if you want to change it, pass it as a parameter.
    Add a response to the button in the activity

    Case R.id.button3: {            fileutil.writetosdcardfile ("Forexample", "test.txt",                       edittext.gettext (). toString (), " UTF-8 ", true);            Toast.maketext (This, "WriteFile", Toast.length_short). Show ();            break;        }         Case R.ID.BUTTON4: {            textview.settext (fileutil.readfromsdcardfile ("Forexample", "test.txt"));            Toast.maketext (This, "ReadFile", Toast.length_short). Show ();            break;        }

    Write "I am CPACM" on the text edit box, click the WriteFile button First, then click ReadFile to get the result of running.

    At the same time in the root directory of the Forexample folder will find Test.txt, which has "I am CPACM" line of words. To this, the file reads and writes successfully.
    (2) file reading and writing in the Application Data directory
    The private data directory stored in the application directory is usually not read and written directly through the file class, but is manipulated using some encapsulated classes or functions. It is generally possible to execute through Context.openfileoutput.
    Add two methods to the activity, reading and writing the files, respectively

        public void WriteFile (String filename,string writestr) {         try{                 fileoutputstream fout =openfileoutput (FileName, Mode_private);                 byte [] bytes = Writestr.getbytes ();                 Fout.write (bytes);                 Fout.close ();               }                 catch (Exception e) {                 e.printstacktrace ();                }         }         Read Data public    string ReadFile (String fileName) {       string res= "";       try{              fileinputstream fin = openfileinput (fileName);              int length = fin.available ();              byte [] buffer = new Byte[length];              Fin.read (buffer);                  res = encodingutils.getstring (buffer, "UTF-8");              Fin.close ();              }          catch (Exception e) {              e.printstacktrace ();          }          return res;     }

    Also add in the response of the button

    Case R.ID.BUTTON5: {            WriteFile ("Test2.txt", Edittext.gettext (). toString ());            Toast.maketext (This, "Writeprivatefile", Toast.length_short). Show ();            break;        }         Case R.ID.BUTTON6: {            textview.settext (readFile ("test2.txt"));            Toast.maketext (This, "Readprivatefile", Toast.length_short). Show ();            break;        }

    Follow the same picture.

    Finally, don't forget to declare permissions in the configuration file

    <uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/><uses-permission android: Name= "Android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
Second, the use of Android settings files

Users often have some personal preferences when they use the app. In order to meet the needs of different users, the application usually provides the corresponding settings (Preference), so that users can choose according to their preferences. These settings are stored locally and displayed in a structured manner so that users can edit them.

  1. set up storage and use of files

    The settings data for Android apps can be represented by the Android.content.SharedPreferences class. It provides a set of data-reading interfaces that can read data such as the number of shapes, Boolean numbers, and so on for a given key value from the settings file.
    The first is to get sharedpreferences
    Private Sharedpreferences UserInfo;
            Called in the interface component or service component, constructs the application default settings file, the default file name is _preferences.xml        //userinfo = Preferencemanager.getdefaultsharedpreferences (this);          Or gets the Sharedpreferences object parameter for the specified name,  respectively, for the stored file name and storage mode.        userInfo = getsharedpreferences ("preferences", activity.mode_private);                 Reads the data and, if it cannot be found, uses the default value        of String username = userinfo.getstring ("name", "Undefined name");          String msg = userinfo.getstring ("msg", "Undefined Information");        Display text        textview.settext (username+ "," +msg);

    Two methods of obtaining, default or specifying a file
    Next Add the response button

    Case R.ID.BUTTON7: {//Get sharedpreferences editor Sharedpreferences.editor editors = Userinfo.edit ();            The information is stored in the corresponding key value editor.putstring ("Name", Edittext.gettext (). toString ()). commit ();            Toast.maketext (This, "SetName", Toast.length_short). Show ();        Break } case R.ID.BUTTON8: {//get sharedpreferences editor sharedpreferences.editor = UserInfo.            Edit ();            The information is stored in the corresponding key value SS editor.putstring ("MSG", Edittext.gettext (). toString ()). commit ();            Toast.maketext (This, "Setmessage", Toast.length_short). Show ();        Break } Case R.id.button9: {
    Get sharedpreferences file UserInfo = getsharedpreferences ("preferences", activity.mode_private); String username = userinfo.getstring ("name", "Undefined name"); String msg = userinfo.getstring ("msg", "Undefined information"); Textview.settext (username+ "," +msg); Toast.maketext (This, "showmsg", Toast.length_short). Show (); Break } Case R.ID.BUTTON10: {
    Output XML file Textview.settext (print ()); Toast.maketext (This, "Showxml", Toast.length_short). Show (); Break }

    Button 7,8 can set the information, button 9 reads the information from the Sharedpreferences file and displays it in the text box. Button 10 displays all the information in this XML file.


    access to preference in other applications (Access to Firstapp data in Secondapp), if Firstapp preference was created with context.mode_world_readable or context.mode_world_ Writeable permissions.

    For example, in <package name> for Com.first.app, a preference ("First_app_perferences") was created using the following statement.

    Java code getsharedpreferences ("First_app_perferences", context.mode_world_readable);

    To access preference in the Firstapp app in Secondapp, you first need to create a context for the Firstapp app and then access preference through the context, Access to preference will be found in the Shared_prefs directory under your app's package preference

    Context Firstappcontext = Createpackagecontext ("Com.first.app", context.context_ignore_security);   Sharedpreferences sharedpreferences = firstappcontext.getsharedpreferences ("First_app_perferences",  context.mode_world_readable);   String name = sharedpreferences.getstring ("name", "");  

    If you do not access the Firstapp app's preference by creating a context, you can directly access the preference corresponding XML file for the Firstapp app in the form of a read XML file.

    Such as:
    File XMLFile = new file ("/data/data/<package name>/shared_prefs/first_app_perferences.xml");//<package name > should be replaced with the app's package name: Com.first.app

  2. Set interface Components
    There is a special kind of preference object: Android.preference.PreferenceGroup. It is a container-type preference object that is responsible for managing a set of associated preference objects. Sets the interface component for item editing, which is typically derived from the Android.preference.PreferenceActivity class. It can transform a custom set tree into a corresponding control to render it.
    public class Preferencesdemo extends preferenceactivity{     @Override public     void OnCreate (Bundle Savadinstancestate) {         super.oncreate (savadinstancestate);         This.addpreferencesfromresource (r.xml.preference);     }}

"Android Zero-single-row development diary"--android data Storage (top)

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.