Android notes-data storage in Android (3), android notes

Source: Internet
Author: User
Tags domian

Android notes-data storage in Android (3), android notes

The Android system integrates a lightweight database:SQLiteTherefore, Android supports databases very well and every application can use it conveniently. As an embedded database engine, SQLite is applicable to the access to a proper amount of data on devices with limited resources. Currently, mainstream mobile devices such as Android and iPhone use SQLite as the storage engine for complex data, and it is stored in mobile phone memory.

In actual development projects, a large amount of data needs to be read and written, and a large number of users need to be concurrently stored. Data should not be stored in the SQLite database of mobile devices such as mobile phones. The storage and computing capabilities of mobile devices are insufficient for them to act as servers. Although SQLite supports most of the SQL-92 syntax, you can also use SQL statements, and other major SQL databases are no different. However, SQLite does not need to install or start the server process like Oracle or MySQL databases. SQLite database is just a file.

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

For devices with limited resources;

No server process;

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

Cross-platform;

Easy to operate. Use standard CRUDE statements, ContentResolver. query (), update (), delete () insert ().

There are other features: high efficiency, which is undeniable; it is very suitable for storing structured data; it is convenient to transfer data between different activities and even different applications.

 

When we develop applications for mobile devices, we may need to use SQLite to store a large amount of data. Therefore, we need to master the SQLite development skills on mobile devices.

Can act as a server

 

In addition, the performance is good only when a small amount of memory is used.

 

1.3 example 4. SQLite Database :3.1 Case: Create an SQLite Database

    

  • The api required to create a database: SQLiteOpenHelper

    • You must define a constructor:

      // Arg2: name of the database file // arg3: cursor factory // arg4: database version public MyOpenHelper (Context context, String name, CursorFactory factory, int version ){}
    • The onCreate method is called when the database is created.
    • The onUpgrade method is called during Database Upgrade.
  • Steps for creating a database:
// Create the OpenHelper object MyOpenHelper oh = new MyOpenHelper (getContext (), "person. db ", null, 1); // obtain the database object. If the database does not exist, create and obtain the database first. If yes, obtain SQLiteDatabase db = oh. getWritableDatabase ();
  • GetWritableDatabase (): Open a database that can be read or written.
  • GetReadableDatabase (): Open the read-only database when the disk space is insufficient. Otherwise, the read/write database can be opened.
  • Create a table when creating 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 a MyOpenHelper class to inherit from SQLiteOpenHelper
Package com. bokeyuan. createsqlite; import android. content. context; import android. database. sqlite. SQLiteDatabase; import android. database. sqlite. SQLiteDatabase. cursorFactory; import android. database. sqlite. SQLiteOpenHelper; public class MyOpenHelper extends SQLiteOpenHelper {public MyOpenHelper (Context context, String name, CursorFactory factory, int version) {// name: name of the database file // factory: cursor factory // version: database version super (context, name, factory, version); // when TODO Auto-generated constructor stub} // when the database is created, this method calls @ Override public void onCreate (SQLiteDatabase db) {// TODO Auto-generated method stub System. out. println ("database created ");
// Create a table
Db.exe cSQL ("create table person (_ id integer primary key autoincrement, name char (10), phone char (20), money integer (10 ))");} // this method is called during Database Upgrade @ Override public void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) {// TODO Auto-generated method stub System. out. println ("database upgraded ");}}
    • The foreground view layout is no longer used here, and the unit test framework is used directly.

Create Test. java in the com. bokeyuan. createsqlite. domian package and inherit the AndroidTestCase class.

      

Package com. bokeyuan. createsqlite. domian; import com. bokeyuan. createsqlite. myOpenHelper; import android. database. sqlite. SQLiteDatabase; import android. test. androidTestCase; public class Test extends AndroidTestCase {public void Test () {// create a database // 1. create an OpenHelper object // obtain a virtual context MyOpenHelper oh = new MyOpenHelper (getContext (), "people. db ", null, 2); // 2. create a database // if the database does not exist, create it first, and then open it. If the database already exists, directly open SQLiteDatabase db = oh. getWritableDatabase (); // If the disk is insufficient, the database is read-only // SQLiteDatabase db = oh. getReadableDatabase ();}}
    • Set the instruction set and library in the configuration 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"?> <Manifest xmlns: android = "http://schemas.android.com/apk/res/android" package = "com. bokeyuan. createsqlite "android: versionCode =" 1 "android: versionName =" 1.0 "> <uses-sdk android: minSdkVersion =" 19 "android: targetSdkVersion = "19"/> <instrumentation android: name = "android. test. instrumentationTestRunner "android: targetPackage =" com. bokeyuan. createsqlite "> </instrumentation> <application android: allowBackup =" true "android: icon =" @ drawable/ic_launcher "android: label =" @ string/app_name "android: theme = "@ style/AppTheme"> <uses-library android: name = "android. test. runner "/> <activity android: name = ". mainActivity "android: label =" @ string/app_name "> <intent-filter> <action android: name =" android. intent. action. MAIN "/> <category android: name =" android. intent. category. LAUNCHER "/> </intent-filter> </activity> </application> </manifest>View Code

The database is stored in data/<project folder>/databases. We can open it with SQLite Professional.

      

When a database is created, the onCreate () method is called and the database is created.

      

      
Change version to 2, Run As → Android JUint Test, call the onUpgrade () method, and the database is upgraded.

// 1. Create an OpenHelper object
// Obtain a virtual context
MyOpenHelper oh = new MyOpenHelper (getContext (), "people. db", null, 2 );

           

 

 

 

 

 

 

 

 

 

References

Data storage and interface display based on Android Application Development (III)

Data Storage Technology for Android

Detailed description of SQLite applications in Android

Summary of five Android Data Storage Methods

Android Development Notes: Data Storage Methods

 

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.