How data is stored in Android note--android (iii)

Source: Internet
Author: User
Tags sqlite database domian

Android System integrates a lightweight database:SQLite, so Android support for the database is very good, each application can easily use it. As an embedded database engine, SQLite is dedicated to the right amount of data access on devices with limited resources, and now mainstream mobile devices like Android, iphone and so on are using SQLite as a storage engine for complex data, and it is stored in cell phone memory.

Well, there's a lot of data in real-world development projects that need to read and write, and you need to face a lot of users ' concurrent storage. The data should not be stored in the SQLite database of mobile devices such as mobile phones, and the storage capacity and computing power of mobile devices are not enough to serve as server roles. Although SQLite supports most of the SQL-92 syntax, you can also use SQL statements that are no different from the other major SQL databases. But SQLite does not need to install, start the server process as Oracle, MySQL database, SQLite database is just a file.

To sum up, we can summarize the characteristics of the SQLite database:

For equipment with limited resources;

No server processes;

All data is stored in the same file and can be freely reproduced;

    Cross-platform;

Easy to operate, using standard crude statements, Contentresolver.query (), update (), delete () insert ().

There are other features: excellent efficiency, which is undeniable; it is ideal for storing structured data and for transferring data between different activity and even different applications.

When we are developing applications for mobile devices, we may want to use SQLite to store our large amounts of data, so we need to master the SQLite development techniques on mobile devices

can act as a server

And it has good performance with very little memory.

1.3 Examples 4. SQLite database :3.1 case: Creating a SQLite database

    

    • Api:sqliteopenhelper to use to create a database

      • You must define a construction method:

        //arg2:数据库文件的名字//arg3:游标工厂//arg4:数据库版本public MyOpenHelper(Context context, String name, CursorFactory factory, int version){}
      • Called when the database is created: OnCreate method
      • Called when the database is upgraded: Onupgrade method
    • To create a database step:
    //创建OpenHelper对象    MyOpenHelper oh = new MyOpenHelper(getContext(), "person.db", null, 1);    //获得数据库对象,如果数据库不存在,先创建数据库,后获得,如果存在,则直接获得    SQLiteDatabase db = oh.getWritableDatabase();
    • Getwritabledatabase (): Open a writable database
    • Getreadabledatabase (): Open read-only database when disk space is low, otherwise open read-write database
    • Create a table when you create a database

      public void onCreate(SQLiteDatabase db) {    // TODO Auto-generated method stub    db.execSQL("create table person (_id integer primary key autoincrement, name char(10), phone char(20), money integer(20))");}
    • Code:
      • Create Myopenhelper class inheritance Sqliteopenhelper
 PackageCom.bokeyuan.createsqlite;ImportAndroid.content.Context;Importandroid.database.sqlite.SQLiteDatabase;Importandroid.database.sqlite.SQLiteDatabase.CursorFactory;ImportAndroid.database.sqlite.SQLiteOpenHelper; Public classMyopenhelperextendsSqliteopenhelper { PublicMyopenhelper (Context context, String name, Cursorfactory factory,intversion) {        //Name : Names of database files//Factory: Cursor Factory//version: The revision number of the database        Super(context, name, Factory, version); //TODO auto-generated Constructor stub    }    //when the database is created, this method calls@Override Public voidonCreate (Sqlitedatabase db) {//TODO auto-generated Method StubSYSTEM.OUT.PRINTLN ("Database was created");
Create a table
Db.execsql ("CREATE TABLE Person" (_id integer primary key autoincrement, name Char (TEN), Phone char (), Money Integer (10)) ") ; } //when the database is upgraded, this method calls@Override Public voidOnupgrade (Sqlitedatabase db,intOldversion,intnewversion) { //TODO auto-generated Method StubSYSTEM.OUT.PRINTLN ("Database Upgraded"); }}
      • The front view layout is no longer used, and the unit test framework is used directly.

Create the Test.java in the Com.bokeyuan.createsqlite.domian package and inherit the Androidtestcase class.

      

 PackageCom.bokeyuan.createsqlite.domian;ImportCom.bokeyuan.createsqlite.MyOpenHelper;Importandroid.database.sqlite.SQLiteDatabase;Importandroid.test.AndroidTestCase; Public classTestextendsAndroidtestcase { Public voidTest () {//Create a database//1. Create a Openhelper object//get a virtual contextMyopenhelper Oh =NewMyopenhelper (GetContext (), "people.db",NULL, 2); //2. Create a database//If the database does not exist, create it first, then open it, if the database already exists, open the side directlySqlitedatabase db =oh.getwritabledatabase (); //If the disk is low, the database is read-only//Sqlitedatabase db = Oh.getreadabledatabase ();    }}
      • Set the instruction set and library in the manifest file Androidmanifest.xml:

<instrumentation
Android:name= "Android.test.InstrumentationTestRunner"
Android:targetpackage= "Com.bokeyuan.createsqlite" ></instrumentation>

<uses-library android:name= "Android.test.runner"/>

<?XML version= "1.0" encoding= "Utf-8"?><Manifestxmlns:android= "Http://schemas.android.com/apk/res/android" Package= "Com.bokeyuan.createsqlite"Android:versioncode= "1"Android:versionname= "1.0" >    <USES-SDKandroid:minsdkversion= "+"android:targetsdkversion= "+" />    <InstrumentationAndroid:name= "Android.test.InstrumentationTestRunner"Android:targetpackage= "Com.bokeyuan.createsqlite"></Instrumentation>    <ApplicationAndroid:allowbackup= "true"Android:icon= "@drawable/ic_launcher"Android:label= "@string/app_name"Android:theme= "@style/apptheme" >        <uses-libraryAndroid:name= "Android.test.runner" />        <ActivityAndroid:name=". Mainactivity "Android:label= "@string/app_name" >            <Intent-filter>                <ActionAndroid:name= "Android.intent.action.MAIN" />                <categoryAndroid:name= "Android.intent.category.LAUNCHER" />            </Intent-filter>        </Activity>    </Application></Manifest>
View Code

The database is stored under the data/< project folder >/databases/. We can open it with SQLite professional.

      

When the database is created, this method call indicates that the OnCreate () method was called and the database was created

      

      
After changing the version to 2,run as→android juint test, call the Onupgrade () method and the database is upgraded

1. Create a Openhelper object
Get a virtual context
Myopenhelper Oh = new Myopenhelper (GetContext (), "people.db", NULL, 2);

           

Resources

Data storage and interface presentation based on Android application development (III.)

Android for data storage technology

A detailed description of the SQLite app in Android

Five ways to summarize Android data storage

Android Development Note: A detailed description of how data is stored

How data is stored in Android note--android (iii)

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.