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

Source: Internet
Author: User
Tags name database

Needless to say, the operation of the database is immediately followed. Come on!When it comes to data storage problems, the database has to be mentioned. A database is an ideal tool for storing relational data. Android provides a powerful database support for developers to easily construct database-based applications. Android's database application, based on the most popular open source embedded database SQLite. In Android, the app's database file is private to the app and is stored in the databases subdirectory under the app data directory. From the code structure, the Android database implementation can be divided into two levels, at the bottom through C + + Call SQLite interface to execute the SQL statement, and through JNI up exposed Java accessible interface.I. Use of Android database

Android uses Android.database.sqlite.SQLiteDatabase to represent a database object, which provides two modes to help developers perform basic database operations such as pruning and checking.

  1. Describing operations with SQL statements
    Use SQL statements to invoke Sqlitedatabase.execsql or sqlitedatabase.rawquery to perform operations.
    Use SQL to query the data, cursor data = Db.rawquery ("Select id,name from Table");//Use SQL to insert Data db.execsql ("INSERT into Contacts (Id,name) VALUES (2, ' CPACM ') ");
    People who have learned a bit about SQL statements should be able to read the above code (in fact, the meaning of the statement can also know a ~)
    Here I explain the role of the cursor (cursor), the cursor can not be the name (up at the time when learning the database cursor as a pointer variable in C, although a bit right, but the meaning is still wrong), cursor it is the system for users to open a data buffer, yes, It is a data region that holds the execution result of the SQL statement. But it also provides a mechanism for extracting one record at a time from a result set that includes multiple data records, which is similar to a pointer. Cursors are always associated with an SQL selection statement because the cursor consists of a result set (which can be 0, one, or multiple records retrieved by a related selection statement) and a cursor position in the result set that points to a particular record. When you decide to process a result set, you must declare a cursor that points to the result set. In the case of a C language, if you write a program that handles a file, the cursor is just like the file handle you get when you open the file, and the file handle represents the file as long as the file opens successfully. In short, the cursor is a piece of data area with a unique notation that allows the user to read the data from one article to the other.
  2. structured way to describe the operation of a database
    This way, even if we are unfamiliar with SQL statements, we can use the most familiar object-oriented approach to database operations.
    Structured way to query the data of cursor: Db.query ("Contacts", new string[]{"id", "name"},null,null,null,null,null);// Structured way to insert data contentvalue values = new Contentvalues () values.put ("id", 2), Values.put ("name", "CPACM");d b.insert ("table" , null,values);
    /*** Parameter Description * Table: Data table name, columns: The column name that needs to be displayed, if NULL is equivalent to * * selection: The Where condition of the SQL statement; The Selectionargs array puts the where condition to replace? Number * Groupby:sql Statement Group, ORDER by: Sort, default asc**/public Cursor query (string table, string[] columns, string selection, string[ ] Selectionargs, String groupBy, String having, string-by-clause) {
    }

    For example, the SQL statement I want to query is

    SELECT CustomerName, SUM (orderprice) from Orders WHERE country=?       GROUP by CustomerName have       SUM (orderprice) >500      ORDER by CustomerName  

    So I wrote the following code

    Data table name string table =  "Orders";  Column name to display string[] columns = new  string[] {"CustomerName",  "SUM (Orderprice)"};  Select the condition string selection = "country=?";  The variables in the corresponding conditions of the question mark, the number of times please one by one seated. string[] Selectionargs = new  string[]{"China"};  Group name string groupBy = "CustomerName";  The conditions for grouping string having = "SUM (orderprice) >500";  Sort by field string by order = "CustomerName";  Cursor c = db.query (table, columns, selection, Selectionargs, GroupBy, having, by-and-by);  

    This will enable the database to be queried. The other statement parameters are similar, here is not introduced.

    Public long Insert (string table, String nullcolumnhack, contentvalues values)
    public int Delete (string table, String Whereclause, string[] whereargs)
    public int update (string table, contentvalues values, String whereclause, string[] whereargs)

    Extracurricular knowledge : About GroupBy and having the use of
    Group by the name is grouped by XXX, it must have an aggregate function to work with, and at least one group Identification field is required for use. Aggregate functions are: sum (), COUNT (), AVG (), and so on, using group by to summarize the data in groups. For example the above SQL statement CustomerName, if it has four rows {"Zhang San", "John Doe", "Zhang San", "John Doe"}, then this will be divided into two groups, respectively, Zhang San Group and Li four groups, and then the sum of the orderprice they use. The
    having the function is to specify a condition for each group, like where to specify the condition, that is, you can select rows based on criteria you specify. If you want to use the HAVING clause, it must be behind the GROUP BY clause. or the above SQL statement, if Zhang San's sum (orderprice) does not exceed 500, then the three groups will not be displayed.

  3. Pre-compiling of SQL statements
    In practice, some SQL statements need to be reused, in order to avoid the overhead of repeatedly parsing SQL statements, you can precompile the SQL statements that need to be reused to improve the execution efficiency of database operations.
    Compile complex SQL statements sqlitestatement Compiledsql = db.compilestatement (asql);//execute Sqlcompiledsql.execute ();

    In addition, Android offers a rich range of advanced database features, such as support for triggers, support for composite indexes, and support for processing of database transactions.

         try{            db.begintransaction ();            Perform related database operations, and if there are exceptions, go directly to the finally section.        }finally{            //success is called Endtransaction to end transaction            db.endtransaction ();        }

    Extracurricular knowledge : The so-called transaction is a user-defined sequence of database operations, these operations are either done or not done, is an inseparable unit of work. For example, in a relational database, a transaction can be an SQL statement, a set of SQL statements, or an entire program. For example, if you want to modify two different tables in the database at the same time, if they are not a transaction, when the first table is modified, but the second table modification has an exception and cannot be modified, only the second table is returned to the unmodified state, and the first table has been modified. And when you set them up as a transaction, when the first table is modified, but the second table modification has an exception and cannot be modified, the first table and the second table are going back to the unmodified state! This is called a transaction rollback.

  4. Sqliteopenhelper
    In Sqliteopenhelper, a Sqlitedatabase object is encapsulated with the ability to perform operations on the database by using this class.
    Package Com.example.notebook;import Android.content.context;import Android.database.sqlite.sqlitedatabase;import Android.database.sqlite.sqliteopenhelper;import Android.database.sqlite.sqlitedatabase.cursorfactory;public    Class DBHelper extends sqliteopenhelper{private static final int version=1; /** * In Sqliteopenhelper subclasses, you must have this constructor * @param context Context Object * @param name Database name * @param facto RY * @param version of the current database, the value must be an integer and an incremented state */public DBHelper (Context context,string name,cursorfactory FA    Ctory,int version) {super (context,name,factory,version);      } public DBHelper (context context, String name, int. version) {this (context,name,null,version);      } public DBHelper (context context, String name) {this (context,name,version); @Override public void OnCreate (Sqlitedatabase db) {////database is first constructed, this function is called, where you can construct tables, indexes, and so on SYSTEM.OUT.P          Rintln ("Create a Database"); The execsql is used to perform sqL Statement db.execsql ("CREATE Table notebook (_id integer primary key autoincrement,pic varchar (), title varchar (), con            Tent text,time varchar) "); } @Override public void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {//If the given current database version is higher than the existing database    version, call the function System.out.println ("Upgrade a Database"); }  }
  5. Sqliteopenhelperthe application
    Create a new database management class Dbmanager
    Package Com.example.notebook;import Android.content.contentvalues;import Android.content.context;import Android.database.cursor;import Android.database.sqlite.sqlitedatabase;import Android.database.sqlite.sqliteexception;import Android.util.log;public class DBManager {private Context Mcontext = nul        L Private Sqlitedatabase Msqlitedatabase = null;//Object used to manipulate the database private dbhelper DH = null;//Object used to create the database private Strin G DbName = "note.db";//database name private int dbversion = 1;//database Version public DBManager (context context) {Mcontext    = Context; public void Open () {try{DH = new DBHelper (mcontext, dbName, NULL, dbversion);//Establish database if (DH = = null)                {LOG.V ("msg", "is null");            return;        } msqlitedatabase = Dh.getwritabledatabase ();//Open Database//dh.onopen (msqlitedatabase) in writable mode;        }catch (sqliteexception se) {se.printstacktrace ();       }}public void Close () { Msqlitedatabase.close ();//Close Database Dh.close ();    }public cursor SelectAll () {cursor cursor = NULL;        try{//sql statement operation String sql = "SELECT * from Notebook";    cursor = msqlitedatabase.rawquery (sql, NULL);        }catch (Exception ex) {ex.printstacktrace ();    cursor = NULL; } return cursor;    Public Cursor Selectbyid (int id) {//string result[] = {};    cursor cursor = NULL;        try{//sql statement action String sql = "SELECT * from notebook where _id= '" + ID + "'";    cursor = msqlitedatabase.rawquery (sql, NULL);        }catch (Exception ex) {ex.printstacktrace ();    cursor = NULL; } return cursor;    Public long Insert (string title, String content,string pic) {Long datetime = System.currenttimemillis ();    Long L =-1;        try{//Structured mode operation contentvalues CV = new Contentvalues ();        Cv.put ("title", title);        Cv.put ("content", content);        Cv.put ("Time", DateTime);        Cv.put ("Pic", pic); L = Msqlitedatabase.insert ("notebook", NULL, CV);    LOG.V ("datetime", datetime+ "" +l);        }catch (Exception ex) {ex.printstacktrace ();    L =-1;    } return L;    }public int delete (int id) {int affect = 0;    try{//structured mode operation affect = Msqlitedatabase.delete ("Notebook", "_id=?", new String[]{string.valueof (ID)});        }catch (Exception ex) {ex.printstacktrace ();    affect =-1; } return affect;}    public int update (int ID, string title, String content,string pic) {int affect = 0;        try{//Structured mode operation contentvalues CV = new Contentvalues ();        Cv.put ("title", title);        Cv.put ("content", content);        Cv.put ("Pic", pic);        String w[] = {string.valueof (id)};    affect = Msqlitedatabase.update ("Notebook", CV, "_id=?", W);        }catch (Exception ex) {ex.printstacktrace ();    affect =-1; } return affect;}}

    Get Data sample

    Private DBManager DM = null;//Database Management Object
    private cursor cursor = NULL;
    DM = new DBManager (this);//Database Operation object Dm.open ();//Open Database operation object cursor = Dm.selectall ();//Get All data Cursor.movetofirst ();//move the cursor to the first data, you must call int count = Cursor.getcount () before use,//number ArrayList <String> contents = new arraylist<string> ();//All collections of the picture arraylist<string> IMGs = new arraylist& Lt String> ();//All collections of the picture arraylist<string> items = new arraylist<string> ();//All collections of the title Array List<string> times = new arraylist<string> ();//All sets of time for (int i= 0; i < count; i++) { Contents.add (Cursor.getstring (Cursor.getcolumnindex ("content")); Imgs.add (Cursor.getstring (Cursor.getcolumnindex ("pic")); Items.Add (Cursor.getstring (Cursor.getcolumnindex ("title")); Times.add (Cursor.getstring (Cursor.getcolumnindex ("Time"));
    Cursor.getint (Cursor.getcolumnindex ("_id")) Cursor.movetonext ();//pointing the cursor to the next} Dm.clo SE ();//Close Data manipulation object
  6. Concurrency Issues for databases
    Concurrency is one of the most difficult problems to use in a database process, and if you encounter a android.database.SQLException exception in development and prompt "database is locked", it is likely that a deadlock in the database is causing the unreachable. The reason is that SQLite will lock the read and write of the file to prevent the data from being corrupted. In the Android framework layer Sqlitedatabase will lock all database objects, once there are multiple Sqlitedatabase objects pointing to the same database are used in multiple threads, then the sqlitedatabase lock protection is skipped, Causes the database to have a locked exception. So in practice, there is only one Sqlitedatabase object that needs to be guaranteed to access the database at the same time. (You can use global variables to save database objects and use the same connection throughout the data source object)
    Extracurricular Trivia: The tool Sqlite3 is available in the Android SDK, and in shell mode, the database can be added and hacked.
    CMD->ADB Shell->sqlite3 < path >/< database name >->sqlite > select * from Sqmple;
Second, the Android data cloud service

In essence, cloud storage is the storage of data on mobile devices on a remote server over a network. In Android, additional accessibility features make the entire process easier to implement. The first is to identify the user through a Google account. In Android, the default is to support the use of Google account as the identity of the user identity, the system can be used by various applications on the account system to obtain the user's login information. Second, with Google accounts, developers do not need to build their own backend service system.

Android's cloud data access is managed centrally by the system service Backupmanagerservice. When an app submits a backup data request, Backupmanagerservice puts the request into the backup queue, which is submitted to the cloud in accordance with certain control logic. When a new application is installed to the system, the data recovery event is triggered, and the Backupmanagerservice uses the app package name and user account to remove the corresponding backup data from the cloud and try to recover.

In practice, Android constructs an object derived from the subclass Android.app.backup.BackupAgentHelper of the Backupagent class to make it easier to build cloud storage components.

Import Java.io.file;import Java.io.ioexception;import Android.app.backup.backupagenthelper;import Android.app.backup.backupdatainput;import Android.app.backup.backupdataoutput;import Android.app.backup.filebackuphelper;import Android.os.parcelfiledescriptor;public class MyBackupAgent extends        Backupagenthelper {private static final String KEY = "My_backup"; @Override public void OnCreate () {//constructs a file read-write object, declares the file that needs to be backed up filebackuphelper helper = new Filebackuphelper (th        IS, "Backup_file");        Addhelper (Key,helper);    Super.oncreate (); } @Override public void Onbackup (Parcelfiledescriptor oldstate, backupdataoutput data, Parcelfiledesc    Riptor newstate) throws IOException {//Call the parent class method, submit the entire file to the cloud Super.onbackup (oldstate, data, newstate); } @Override public void Onrestore (backupdatainput data, int appversioncode, Parcelfiledescriptor newstate ) throws IOException {//Call the parent class method to overwrite the file obtained from the cloud with the local file Super.onRestore (data, Appversioncode, newstate); } @Override public void Onrestorefile (parcelfiledescriptor data, long size, File destination, int type, l Ong mode, long Mtime) throws IOException {//TODO auto-generated method stub super.onrestorefile    (data, size, destination, type, mode, mtime); }

Android does not submit data to the cloud on its own, and developers need to explicitly call Android.app.backup.BackupManager's datachanged function to trigger.

As with all components, cloud storage components are managed by the system. This involves putting the relevant information for the component into the configuration file.

<application android:backupagent = "Mybackupagent" ...>

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

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.