How Android data is stored

Source: Internet
Author: User
Tags sqlite database xml parser sqlite manager

Data storage is most frequently used in development, and here are 5 ways to implement data storage in the Android platform, namely: 1 store data using sharedpreferences 2 File store data 3 SQLite database store data 4 Using ContentProvider to store data 5 networked storage data Preference,file, database these three ways the corresponding directory is:? /data/data/package name/shared_pref? /data/data/package name/files? /data/data/package Name/database
About these five kinds of data storage methods, according to the actual situation to choose the most appropriate, uphold the simplest principle, that is, can be handled in a simple way, do not use a complex way. such as storing a few data or simple objects, with sharedpreference can do, there is no need to write a contentprovider.
? Simple data and configuration information, sharedpreference is preferred;? If Sharedpreferences is not enough, create a database;? Structured data, be sure to create a database, although this slightly annoying lock, but the benefits are endless;
? Files are used to store files (that is, non-configuration information or structured data), such as text files, binaries, PC files,
multimedia files, downloaded files, etc... Try not to create files;
?  If a file is created, if it is a private file or an important file, it is stored on-premises, otherwise it is stored externally.   The first type: using Sharedpreferences to store data sharedpreferences is a lightweight storage class on the Android platform, mainly to save some common configuration such as window state, usually in the activity Reload window state onsaveinstancestate save is generally done using sharedpreferences, which provides the Android platform General Long shaping, int shaping, string-string saving.   What is the way it is handled? Sharedpreferences is similar to the previous INI configuration file on Windows systems, but it is divided into multiple permissions, can be globally shared access, android123 hints are ultimately stored in XML, overall efficiency is not particularly high, It's a lot better for regular lightweight than SQLite, if you really don't have enough storage to consider your own definition file format. XML processing is Dalvik through the native XML parser, such as the Xmlpull method, which is better for memory resource consumption.   Its essence is to store Key-value key-value pairs of data based on XML files, typically to store some simple configuration information. Its storage location is under the/data/data/< >/shared_prefs directory. The Sharedpreferences object itself can only fetch data without supporting storage and modification, and storage modifications are implemented through the editor object.   The steps to implement Sharedpreferences storage are as follows: First, get Sharedpreferences object according to context. Use the edit () method to get the editor object. Third, through the editor object store Key-value key value pair data. Iv. submit data through the commit () method.   Below is the sample code:  public class Mainactivity extends Activity {     @Override      public void OnCreate (Bundle savedinstancestate) {        super.oncreate (savedinstancestate);        Setcontentview (R.layout.main);               // Get Sharedpreferences object         Context ctx = mainactivity.this;               Sharedpreferences sp = ctx.getsharedpreferences ("sp", mode_private );       //Deposit Data         Editor editor = Sp.edit ();        Edit Or.putstring ("String_key", "STRING");        editor.putint ("Int_key", 0);        Editor.putboolean ("Boolean_key", true);        editor.commit ();       & nbsp;       //Returns the value of String_key         LOG.D ("SP", Sp.getstring ("String_key", " None "));       //If Not_exist does not exist, the return value is" none "        LOG.D (" SP ", Sp.getstring (" Not_exist "," none "));     } }      After this code is executed, the/data/data/com.test/shaA sp.xml file is generated under the Red_prefs directory, and an application can create multiple such XML files. Compared with SQLite database,  sharedpreferences object is more convenient and concise than creating database, creating table, writing SQL statement and so on. But Sharedpreferences also has its own flaws, such as its functional storage boolean,int,float,long and string five of simple data types, such as its inability to perform conditional queries. So no matter how simple the sharedpreferences data store operation is, it can only be a supplement to the storage method, and it cannot completely replace other data storage methods such as SQLite database.   Second: File storage data about file storage, activity provides a openfileoutput () method that can be used to output data to a file, the implementation process is the same as in the J2SE environment to save data to the file. Files can be used to store large amounts of data, such as text, pictures, audio, and so on. The default location is:/data/data/< >/files/***.***.   code example:  public void Save ()  {         Try {            FileOutputStream outstream=this.openfileoutput ("A.txt", context.mode_world_readable);            Outstream.write (Text.gettext (). toString (). GetBytes ());            Outstream.close ();            Toast.maketext (myactivity.this, "Saved", Toast.length_long ). Show ();       } catch (FileNotFoundException e) {           return;       }        catch (IOException e) {    & nbsp       return;       }  }    openfileoutput () The first parameter of the method is used to specify the file name, cannot contain the path delimiter "/", and if the file does not exist, Android will automatically create it. The created file is saved in the/data/data//files directory, such as:/data/data/cn.itcast.action/files/itcast.txt, by clicking the Eclipse Menu "window"-"Show View"-" Other ", expand the Android folder in the Conversation window, select the File Explorer view below, and then expand the/data/data//files directory in File Explorer view to see it. The second parameter of the  openfileoutput () method specifies the mode of operation, with four modes: context.mode_private = 0context.mode_append = 32768context.mode_ world_readable = 1context.mode_world_writeable = 2context.mode_private: The default mode of operation, which means that the file is private and can only be accessed by the app itself, in that mode, The content that is written overwrites the contents of the original file, if you want to append the newly written content to the original file. You can use Context.MODE_APPENDContext.MODE_APPEND: mode checks whether a file exists, appends content to the file, or creates a new file. Context.mode_world_readable and context.mode_world_writeable are used to control whether other apps have permission to read and write to the file. Mode_world_readable: Indicates that the current file can be read by another application; Mode_world_writeable: Indicates that the current file can be written by another application.   If you want the file to be read and written by another app, you can pass in: Openfileoutput ("Itcast.txt", context.mode_world_readable + context.mode_world_writeable); Android has its own security model, and when the application (. apk) is installed, the system assigns him a userid, which requires a UserID match when the app is going to access other resources such as files. By default, any file created by the app, Sharedpreferences, should be private (in/data/data//files) and other programs cannot access it. Unless you specify context.mode_world_readable or context.mode_world_writeable at creation time, only such other programs can access them correctly.   Read File example:  public void Load () {    try {        FileInputStream instream= This.openfileinput ("A.txt");        Bytearrayoutputstream stream=new bytearrayoutputstream ();         byte[] buffer=new byte[1024];        int Length=-1;while (length=instream . Read (buffer))!=-1)   {            Stream.Write (buffer,0,length);       }         stream.close ();        instream.close ();    &NBSP ;   Text.settext (stream.tostring ());        Toast.maketeXT (Myactivity.this, "Loaded", Toast.length_long). Show ();   } catch (FileNotFoundException e) {    & nbsp   E.printstacktrace ();   }    catch (IOException e) {        return;  & nbsp } }      for private files can only be accessed by the app that created the file, if you want the file to be read and written by another app, you can specify Context.mode_world_ when you create the file Readable and context.mode_world_writeable permissions.  activity also provides the Getcachedir () and Getfilesdir () methods: The Getcachedir () method is used to get the/data/data//cache directory Getfilesdir () method for obtaining/data /data//files directory.   Put the file into SDcard: Use Activity's Openfileoutput () method to save the file, the file is stored in the mobile phone space, the general phone storage space is not very large, small files are also OK, if you want to store such a large file like video, it is not feasible. For large files like video, we can store it in SDcard. What is sdcard for? You can think of it as a removable hard drive or USB stick. To use SDcard in the simulator, you need to first create a SDcard card (not really sdcard, just the image file).   Create SDcard can be created when eclipse creates the emulator, or it can be created using DOS commands, as follows: In the DOS window, enter the tools directory of the Android SDK installation path, and type the following command to create a sdcard with a capacity of 2G. File suffix can be arbitrarily taken, recommended to use. Img:mksdcard 2048M D:\AndroidTool\sdcard.img access to SDcard in your program, you need to request permission to access SDcard.   access to SDcard in Androidmanifest.xml is as follows:  <!--in SCreate and delete file permissions in Dcard-->    <uses-permission android:name= "Android.permission.MOUNT_UNMOUNT_FILESYSTEMS "/>     < Write data permissions to SDcard-->    <uses-permission android:name=" Android.permission.WRITE_EXTERNAL_STORAGE "/>    to SDcard to store files, the program must first determine whether the phone is equipped with sdcard, and can read and write. Note: Access SDcard must have permission to access SDcard in Androidmanifest.xml.     if (Environment.getexternalstoragestate (). Equals (environment.media_mounted)) { File Sdcarddir = Environment.getexternalstoragedirectory ();//Get SDcard directory          file SaveFile = new File (Sdcarddir, "A.txt");        FileOutputStream outstream = new FileOutputStream (save File);        outstream.write ("Test". GetBytes ());        outstream.close ();  }   ? The Environment.getexternalstoragestate () method is used to get the state of the sdcard, and if the phone is loaded with sdcard and can read and write, the method returns a state equal to Environment.media_ Mounted.  environment.getexternalstThe Oragedirectory () method is used to get the directory of the SDcard, of course, to get the SDcard directory, you can also write:   file sdcarddir = new File ("/sdcard"); Get SDcard directory  file saveFile = new file (Sdcarddir, "itcast.txt");  //the above two lines of code can be synthesized one sentence:  file saveFile = new file ("/sdcard/a.txt");  fileoutputstream OutStream = new FileOutputStream (saveFile);  outstream.write ("Test"). GetBytes ());  outstream.close ();    Third: SQLite database storage Data  sqlite is a lightweight embedded database engine that supports the SQL language, And it has good performance with very little memory. It's also open source and can be used by anyone. Many open source projects (Mozilla, PHP, Python) use Sqlite.sqlite to make up the following components: SQL compiler, Kernel, backend, and attachments. SQLite makes it easier to debug, modify, and extend SQLite's kernel by leveraging virtual machines and virtual database engines (VDBE).     features:  resource-constrained devices,  No server process,  all data resides in the same file cross-platform,  can be freely replicated.   sqlite internal structure:   ? SQLite basically conforms to the SQL-92 standard and is no different from the other major SQL databases. It has the advantage of being efficient, and the Android runtime environment contains the full SQLite. The biggest difference between     sqlite and other databases is support for data types, when you create a table, you can specify the data type of a column in the CREATE TABLE statement, but you can put any data type in any column. When a value is inserted into the database, SQLite checks its type. If the type does not match the associated column, SQLite attempts to convert the value to the type of the column. If the conversion is not possible, the value isAs its own type of storage. For example, you can put a string into an INTEGER column. SQLite calls this a "weak type" (Manifest typing.). In addition, SQLite does not support some standard SQL features, especially foreign KEY constraints (FOREIGN key constrains), nested transcaction and right OUTER joins and full OUTER joins, and some ALTER TABLE function. In addition to the above features, SQLite is a complete SQL system with complete triggers, trades, and so on.    android integrated with SQLite database Android at runtime (run-time) integrates SQLite, so each Android application can use the SQLite database.      using SQLite in Android development is fairly straightforward for developers who are familiar with SQL. However, because JDBC consumes too much system resources, JDBC is not suitable for memory-constrained devices such as phones. As a result, Android provides some new APIs to use with the SQLite database, which programmers need to learn to use in Android development. The     database is stored under the data/< project folder >/databases/. Using SQLite database in Android development activites can access a database via Content Provider or Service.     below will explain in detail if you create a database, add data and query the database. Creating a database Android does not automatically provide a database. To use SQLite in an Android application, you must create your own database, and then create tables, indexes, and populate the data.  android provides sqliteopenhelper to help you create a database that you can easily create by inheriting the Sqliteopenhelper class. The Sqliteopenhelper class encapsulates the logic used to create and update databases, based on the needs of the development application. Subclass of    sqliteopenhelper, at least three methods need to be implemented:  1 constructor, calling parent class SQLThe Iteopenhelper constructor. This method requires four parameters: the context (for example, an Activity), the database name, an optional cursor factory (usually Null), and an integer representing the version of the database model you are using. The  2 onCreate () method, which requires a Sqlitedatabase object as a parameter, populates the table and initializes the data as needed. The  3 onupgrage () method requires three parameters, a Sqlitedatabase object, an old version number, and a new version number, so you can clearly see how to transform a database from the old model to the new one.     The following sample code shows how to inherit Sqliteopenhelper to create a database:  public class Databasehelper extends Sqliteopenhelper {& nbsp    Databasehelper (Context context, String name, cursorfactory cursorfactory, int version)    {        Super (context, name, cursorfactory, version);          }                @Override   &NBS p;     public void OnCreate (Sqlitedatabase db) {             //to Do create database, operations on database          }                @Ov Erride     public void Onupgrade (sqlitedAtabase db, int oldversion, int newversion) {             //TODO Change the operation of the database version &nbs P       &NBSP,}            @Override     public void OnOpen (Sqlitedatabase db) {             super.onopen (db),     &NBSP;&N bsp;         //TODO is executed first after each successful opening of the database          }      &NBSP,}       next discusses how to create a table, insert data, delete a table, and more. Call the Getreadabledatabase () or Getwriteabledatabase () method, you can get the Sqlitedatabase instance, and call that method, depending on whether you need to change the contents of the database:  db= (new Databasehelper (GetContext ())). Getwritabledatabase ();       return (db = = null)? False:true;    the above code will return an instance of the Sqlitedatabase class, using which you can query or modify the database. When you have completed the operation of the database (for example, your Activity has been closed), you need to call Sqlitedatabase's close () method to release the database connection. Creating tables and indexes in order to create tables and indexes, you need to call Sqlitedatabase's Execsql () method to execute the DDL statement. If there is no exception, this method does not return a value.      For example, you can do the following code:  db.execsql ("CREATE TABLE mytable (_id INTEGER PRIMARY KEY AutoIncrement, title TEXT, value REAL); ");      This statement creates a table named MyTable with a column named _id and a primary key, which is an automatically growing integer (for example, when you insert a row, SQLite automatically assigns the column), In addition, there are two columns: Title (character) and value (floating point). SQLite automatically creates an index for the primary key column. Typically, the first time you create a database, you create tables and indexes.     If you do not need to change the schema of the table, you do not need to delete tables and indexes. Deleting tables and indexes requires the drop INDEX and drop table statements to be called using the Execsql () method. Add data to the table above the code, you have created the database and the table, now you need to add data to the table. There are two ways to add data to a table.     like creating a table above, you can use the Execsql () method to perform INSERT, update, DELETE, and other statements to update the table's data. The Execsql () method applies to all SQL statements that do not return a result.   Example: Db.execsql ("INSERT into widgets (name, Inventory)" + "VALUES (' sprocket ', 5)");  Another method is to use Sqlitedatabase The Insert (), update (), delete () method of the object. These methods take part of the SQL statement as an argument.     examples are as follows:  contentvalues cv=new contentvalues ()  cv.put (Constants.title, "example TITLE");  cv.put (Constants.value, Sensormanager.gravity_death_star_i);  db.insert ("MyTable", GetNullColumnHack () , CV); &NBThe Sp;update () method has four parameters, namely the table name, the Contentvalues object that represents the column name and value, the optional where condition, and the optional string that populates the where statement, which replaces the "?" in the Where condition. Tag  update () Updates the value of the specified column according to the condition, so the Execsql () method can be used to achieve the same purpose. The WHERE condition is similar to its arguments and other SQL APIs that have been used.     Example:  string[] parms=new string[] {"This is a String"}; db.update ("Widgets", Replacements, " Name=? ", parms);d the use of the Elete () method is similar to update (), using the table name, the optional where condition, and the corresponding string that populates the where condition. Querying the database is similar to INSERT, UPDATE, DELETE, there are two ways to retrieve data from the SQLite database using SELECT.     1. Call the SELECT statement directly using Rawquery (), and use the query () method to build a query.  raw Queries just like the API name, Rawquery () is the simplest solution. With this method you can invoke the SQL SELECT statement.   Example: Cursor c=db.rawquery ("Select name from Sqlite_master where type= ' table ' and name= ' mytable '", null);  in the example above , we query the SQLite system table (Sqlite_master) to check the existence of table tables. The return value is a cursor object, and the method of the object can iterate over the query results. If the query is dynamic, using this method can be very complex.   For example, using the query () method is a lot easier when you need to query for a column that is not sure when the program is compiled. The  regular Queries query () method builds the queries with the SELECT statement segment. The contents of the SELECT statement are the parameters of the query () method, such as the name of the table to be queried, the name of the field to get, the where condition, including the optional positional parametersTo replace the value of the positional parameter in the Where condition, GROUP by condition, having condition. In addition to the table name, other parameters can be null. Therefore, the previous code snippet can be written as:  string[] columns={"ID", "Inventory"};   string[] parms={"Snicklefritz"};   cursor result=db.query ("Widgets", Columns, "Name=?", parms, NULL, NULL, NULL);       using Cursors    no matter how you execute the query, it will return a cursor, which is an Android SQLite database cursor,  using cursors, you can:   by using the GetCount () method to get the number of records in the result set;  through Movetofirst (), MoveToNext (), and Isafterlast () methods to traverse all records;  through Getcolumnnames () Gets the field name;  by Getcolumnindex () to the field number;  through GetString (), GetInt () and other methods to get the value of the current record of the given field;  through The Requery () method re-executes the query to get the cursor;  through the close () method to release the cursor resource;    For example, the following code traverses the MyTable table:   cursor result= Db.rawquery ("Select ID, Name, inventory from MyTable");     result.movetofirst ();     while (!result.isafterlast ()) {         int id=result.getint (0);         String name=result.getstring (1);     & nbsp;   int Inventory=result.getint (2);        //do something useful with these   &nbs P     Result.movetonext ();      }   result.close ();            use SQLite database management tools in Android to develop on other databases, typically using tools to examine and process the contents of a database, Instead of just using the database's API.    using the Android emulator, there are two alternative ways to manage a database.   First, the emulator binds the SQLITE3 console program and can invoke it using the adb shell command. As soon as you enter the shell of the simulator, execute the sqlite3 command on the path to the database.   database files are generally stored in:/data/data/your.app.package/databases/your-db-name If you prefer to use more friendly tools, you can copy the database to your development machine and use Sqlite-aware the client to manipulate it. In this case, you are working on a copy of the database, and if you want your changes to be reflected on the device, you need to back up the database.   Take the database out of the device and you can use the ADB pull command (or do it on the IDE).   Store a modified database to the device, using the ADB push command. One of the most convenient SQLite clients is the FireFox sqlite Manager extension, which can be used across all platforms.



How Android data is stored

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.