5 Types of Android data storage method Rollup _android

Source: Internet
Author: User
Tags commit joins sqlite sqlite database xml parser file permissions sqlite manager

This article describes 5 ways to store data in Android.

Data storage is the most frequently used in development, and here are 5 ways to implement data storage in the Android platform, respectively:

1 Storing data using sharedpreferences
2 File storage Data
3 SQLite Database Storage data
4 Storing data using ContentProvider
5 Networked Storage data

Here will be a detailed introduction.

First: using sharedpreferences to store data
Sharedpreferences is a lightweight storage class on the Android platform, primarily to save some of the most commonly used configurations, such as window state, typically Overloaded window state onsaveinstancestate save is typically done with sharedpreferences, which provides the Android platform with regular long shaping, int shaping, and string-string saving.

What kind of treatment is it? Sharedpreferences similar to the previous INI configuration file on a Windows system, but it is divided into multiple permissions, you can share access globally, android123 hints are ultimately stored in XML, the overall efficiency is not particularly high, It's a lot better for conventional lightweight than SQLite, and if it's really storage, it's not a good concept to define the file format. XML processing is Dalvik through the native XML parser, such as the Xmlpull method, which is good for memory resource occupancy.

Its essence is based on XML file storage Key-value key value pairs of data, usually used to store some simple configuration information.
Its storage location is in the/data/data/< >/shared_prefs directory.
The Sharedpreferences object itself can only fetch data and does not support storage and modification, and storage modifications are implemented through editor objects.

The steps for implementing sharedpreferences storage are as follows:
Step1, get sharedpreferences objects according to context
Step2, use the edit () method to get the editor object.
Step3, storing Key-value key value pairs of data through editor objects.
STEP4, submit data through the commit () method.

Here is the sample code:

public class Mainactivity extends activity {  
 @Override public
   void OnCreate (Bundle savedinstancestate) {
    Super.oncreate (savedinstancestate);
    Setcontentview (r.layout.main);

    Gets the Sharedpreferences object context
    CTX = mainactivity.this;    
    Sharedpreferences sp = ctx.getsharedpreferences ("sp", mode_private);
    Deposit Data
    Editor Editor = Sp.edit ();
    Editor.putstring ("String_key", "STRING");
    Editor.putint ("Int_key", 0);
    Editor.putboolean ("Boolean_key", true);
    Editor.commit ();

    Returns the value of the 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, a sp.xml file is generated in the/data/data/com.test/shared_prefs directory, and an application can create multiple such XML files.

Compared with the SQLite database, the Sharedpreferences object eliminates the creation of databases, tables, SQL statements and many other operations, relatively more convenient and concise. But Sharedpreferences also has its own flaws, such as its functional storage boolean,int,float,long and string Five 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 way it is stored, and it cannot completely replace other data storage methods such as the SQLite database.

The second type: file storage data
With regard to file storage, activity provides a openfileoutput () method that can be used to output data to a file in a way that is the same as saving data to a file in a J2SE environment.
Files can be used to store large amounts of data, such as text, pictures, audio, and so on.
Default location:/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) {return
      ;
    }

 } 

The first parameter of the Openfileoutput () method specifies the file name, cannot contain the path delimiter "/", and if the file does not exist, Android automatically creates it.
The created file is saved in the/data/data//files directory, such as:/data/data/cn.itcast.action/files/itcast.txt, by clicking on 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 is used to specify the mode of operation, with four modes, respectively:

Context.mode_private = 0
Context.mode_append = 32768
context.mode_world_readable = 1
Context.mode_world_writeable = 2

Context.mode_private: For the default mode of operation, the file is private data and can only be accessed by the application itself, in which the written content overwrites the contents of the original file, if you want to append the newly written content to the original file. You can use the Context.mode_append
Context.mode_append: Mode checks whether the file exists, appends to the file, or creates a new file.
Context.mode_world_readable and context.mode_world_writeable are used to control whether other applications have permission to read and write to the file.
Mode_world_readable: Indicates that the current file can be read by other applications;
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 other applications, 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, and when the application accesses other resources such as files, it needs userid matching. By default, any file created by the application, sharedpreferences, should be private (located in/data/data//files) and not accessible by other programs.
Unless context.mode_world_readable or context.mode_world_writeable are specified at the time of creation, only such other programs can access them correctly.

To read a 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 ();
    Text.settext (Stream.tostring ());
    Toast.maketext (Myactivity.this, "Loaded", Toast.length_long). Show ();
  catch (FileNotFoundException e) {
    e.printstacktrace ();
  }
  catch (IOException e) {return
    ;
  }

} 

For private files that can only be accessed by the application that created the file, if you want the file to be read and written by another application, you can specify context.mode_world_readable and Context.mode_world_writeable permissions when you create the file.

The activity also provides Getcachedir () and Getfilesdir () methods: The Getcachedir () method is used to obtain the/data/data//cache directory Getfilesdir () method for obtaining/data/data/ /files directory.

Deposit the file in SDcard:
Use the activity of the Openfileoutput () method to save the file, the file is stored in the mobile phone space, the general mobile phone storage space is not very large, storing small files also line, if you want to store such large files as video, it is not feasible. For large files like video, we can store them in SDcard.
What's sdcard for? You can think of it as a removable hard disk or a USB drive. To use SDcard in the emulator, you need to create a SDcard card (not really sdcard, just a mirrored file).

Creating SDcard can be created with Eclipse creation simulator, or it can be created using DOS commands, as follows: Enter the tools directory of the Android SDK installation path in the DOS window, and enter the following command to create a sdcard with a capacity of 2G File suffix can be arbitrarily taken, recommended use. Img:mksdcard 2048M D:\AndroidTool\sdcard.img access to SDcard in the program, you need to apply for access to SDcard permissions.

The right to join the access SDcard in Androidmanifest.xml is as follows:

 <!--Create and delete file permissions in SDcard-->
  <uses-permission android:name= "android.permission.MOUNT_UNMOUNT_ Filesystems "/>

  <!--write data permissions to SDcard-->
  <uses-permission android:name=" Android.permission.WRITE _external_storage "/> 

To store files to SDcard, the program must first determine whether the phone is fitted with sdcard and can read and write.
Note: Access to SDcard must include access to 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 (savefile);
    Outstream.write ("Test". GetBytes ());
    Outstream.close ();
}

The Environment.getexternalstoragestate () method is used to obtain the state of the sdcard, and if the phone has sdcard and can read and write, the state of the method return equals Environment.media_ Mounted.
Environment.getexternalstoragedirectory () method is used to get the directory of SDcard, of course, to obtain the SDcard directory, you can also write:

File Sdcarddir = new file ("/sdcard"); Gets the SDcard directory
file SaveFile = new file (Sdcarddir, "itcast.txt");
The above two code can synthesize one sentence:
file SaveFile = new file ("/sdcard/a.txt");
FileOutputStream OutStream = new FileOutputStream (savefile);
Outstream.write ("Test". GetBytes ());
Outstream.close ();

The third type: SQLite databases Store data

SQLite is a lightweight embedded database engine that supports the SQL language and has good performance with very little memory. In addition it is open source and can be used by anyone. Many open source projects (Mozilla, PHP, Python) Use the sqlite.sqlite to consist of the following components: SQL compiler, Kernel, backend, and attachment. SQLite makes debugging, modifying, and extending the SQLite kernel easier by leveraging virtual machines and virtual database engines (VDBE).

Characteristics:

For resource-limited devices,

No server process,

All data is stored in the same file across platforms,

can be reproduced freely.

SQLite Internal structure:

SQLite basically conforms to the SQL-92 standard and is no different from other major SQL databases. It has the advantage of being efficient, and the Android runtime environment contains complete SQLite.

The biggest difference between SQLite and other databases is support for data types, where you can specify the data type of a column in a CREATE TABLE statement, but you can put any data type into 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 it cannot be converted, the value is stored as the type it has itself. For example, you can put a string into an INTEGER column. SQLite called this "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, transactions, and so on.

Android integrates the SQLite database with Android at runtime (run-time) integrates SQLite, so every 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 appropriate for a memory-constrained device such as a mobile phone. As a result, Android provides some new APIs to use the SQLite database, and programmers need to learn to use these APIs in Android development.

The database is stored under the data/< project folder >/databases/. The SQLite database is used in Android development activites can access a database through the Content Provider or Service.

The following is a detailed explanation if you create a database, add data, and query the database. Creating a database Android does not automatically provide a database. Using SQLite in an Android application, you must create your own database, and then create tables, indexes, and fill data.

Android provides sqliteopenhelper to help you create a database, and you can easily create a database just by inheriting the Sqliteopenhelper class. The Sqliteopenhelper class encapsulates the logic used to create and update databases, depending on the needs of the development application.

Sqliteopenhelper subclass, you need to implement at least three methods:

1 Constructors , call the constructor of the parent class Sqliteopenhelper. This method requires four parameters: a context environment (for example, an activity), a database name, an optional cursor factory (usually Null), and an integer representing the version of the database model you are using.

2 OnCreate () method , It requires a Sqlitedatabase object as a parameter, populating the table and initializing the data as needed.

3 Onupgrage () method , it takes three parameters, a Sqlitedatabase object, an old version number and a new version number, so you can 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 {  
 Databasehelper (context context, String name, cursorfactory cursorfactory, int version) 
 {   
  Super (context, name, cursorfactory, version);   
   }   

   @Override public  
   void OnCreate (Sqlitedatabase db) {   
     //TODO to create a database, operations on the database are   

   @Override  
 Public void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {   
     //TODO changes the operation of the database version   
   }   

 @Override  
 public void OnOpen (Sqlitedatabase db) {   
     super.onopen (db);    
     TODO first executed after each successful opening of the   
   database   
   

Next, we'll discuss how to create a table, insert data, delete a table, and so on. Call the Getreadabledatabase () or Getwriteabledatabase () method, and you can get the Sqlitedatabase instance, which is specifically called, 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 returns an instance of the Sqlitedatabase class, and you can query or modify the database using this object. When you have finished working on the database (for example, your activity has been turned off), you need to call the Sqlitedatabase close () method to release the database connection. Create tables and indexes to create tables and indexes, you need to invoke the Sqlitedatabase Execsql () method to execute the DDL statement. If there is no exception, this method has no return value.

For example, you can execute the following code:

Db.execsql ("CREATE TABLE mytable (_id INTEGER PRIMARY KEY autoincrement, title TEXT, value real);"

This statement creates a table named MyTable. The table has a column named _id and is a primary key, and the value of this column is an integer that will automatically grow (for example, when you insert a row, SQLite will automatically assign the column), and two more columns: Title (character) and value (floating-point number). SQLite automatically creates an index for the primary key column. Typically, tables and indexes are created the first time a database is created.

If you do not need to change the schema of the table, you do not need to delete the table and index. Deleting tables and indexes requires that the drop INDEX and drop TABLE statements be invoked using the Execsql () method. Add data to the table above the code, you have created the database and tables, you now need to add data to the table. There are two ways to add data to a table.

Like the table above, you can use the Execsql () method to update the table's data by executing the INSERT, UPDATE, and DELETE statements. The Execsql () method applies to all SQL statements that do not return results.

For example: Db.execsql ("INSERT into widgets (name, Inventory)" + "VALUES (' sprocket ', 5)");

Another method is to use the Insert (), update (), delete () method of the Sqlitedatabase 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);

The update () method has four parameters, namely the table name, the Contentvalues object that represents the column name and the value, the optional where condition and the optional string to populate the where statement, which replaces the "? Mark

Update () Updates the value of the specified column according to the criteria, so the Execsql () method can achieve the same purpose. The WHERE condition is similar to its parameters and other used SQL APIs.

For example:

String[] Parms=new string[] {"This is a String"};
Db.update ("Widgets", Replacements, "Name=", parms); 

The Delete () method is used similar to update (), using the table name, the optional where condition, and the corresponding string that fills the where condition. Query database similar to INSERT, UPDATE, DELETE, there are two ways to use SELECT to retrieve data from the SQLite database.

1. Use Rawquery () to invoke the SELECT statement directly, and use the query () method to build a query.

Raw Queries, like the API name, Rawquery () is the simplest solution. In this way you can invoke the SQL SELECT statement.

For 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 whether the table exists. The return value is a cursor object, and the method of this object can iterate through the query results. If the query is dynamic, using this method can be very complicated.

For example, when you need to query a column that is not sure when the program compiles, using the query () method is much easier.

The Regular Queries query () method builds queries with a SELECT statement segment. The SELECT statement is used as a parameter to the query () method, such as the name of the table to be queried, the name of the field to get, the Where condition, and the optional positional parameter, which replaces the value of the position parameter in the Where condition, the GROUP by condition, the having condition. In addition to the table name, other parameters can be null. So, 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, you will return a Cursor, which is the Android SQLite database cursor,

With cursors, you can:

The number of records in the result set is obtained by using the GetCount () method;

Traverse all records through Movetofirst (), MoveToNext (), and Isafterlast () methods;

The field name is obtained by Getcolumnnames ();

Convert to field number by Getcolumnindex ();

The value of the current record of the given field is obtained by means of getString () and getInt ();

The Requery () method is used to rerun the query to get the cursor;

The cursor resource is released through the Close () method;

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); 
int Inventory=result.getint (2); 
Do something useful with these 
result.movetonext (); 
}

Result.close ();

Using the SQLite database management tool in Android for development on other databases, you typically use tools to check and process the content of the database, rather than just using the database's APIs.

With the Android emulator, there are two alternative ways to manage the database.

First, the emulator binds the SQLITE3 console program, which can be invoked 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 a more user-friendly tool, you can copy the database to your development machine and use the Sqlite-aware Client to manipulate it. In this case, you operate on a copy of a database, and if you want your changes to be reflected on the device, you need to back up the database.

Test the database from the device and you can use the ADB pull command (or do it on the IDE).

Stores 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.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.