Sort Android databases and android Databases

Source: Internet
Author: User
Tags exit in

Sort Android databases and android Databases

Today, we have organized database-related operations and code in Android to facilitate future reference. Main content:

1. native database writing

2. Terminal sqlite operations

3. Third-party Libraries

4. Transaction Processing

5. permissions and paths

 

I. native database writing

Generally, you must inherit from SQLiteOpenHelper and write a Helper.

Public class DatabaseHelper extends SQLiteOpenHelper {private static final String name = "crashier"; // database name private static final int version = 1; // database version public DatabaseHelper (Context context) {// The third parameter CursorFactory specifies the factory class for obtaining a cursor instance during query execution. If it is set to null, it indicates that the system uses the default factory class super (context, name, null, version) ;}@ Override public void onCreate (SQLiteDatabase db) {db.exe cSQL ("create table if not exists person (personid integer primary key autoincrement, name varchar (20), age INTEGER) ") ;}@ Override public void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) {db.exe cSQL (" alter table person ADD phone VARCHAR (12 )"); // Add a column to the table }}

After obtaining a database of the SQLiteDatabase type, the general operation is to directly use it to execute a String-type SQL statement.

Native also supports some operation APIs: insert, update, and delete. Parameters need to input data content

ContentValues cv = new ContentValues (); cv. put (TABLE_NUM, 1); cv. put (TABLE_DATA, "Test Database Data"); db. insert (Test, null, cv );

 

2. Terminal sqlite operation 1. device connection

You can view the SDK location through Open Module Settings or File> Project Structure. Then go to the SDK directory from the terminal

$cd /Users/dsx/Library/Android/sdk/platform-tools

Android simulators or pos drivers can be accessed using usb links or wifi. If it is a usb connection, you can directly access it. For a wiki link, use the adb command to connect to the IP address.

$./adb devices  $./adb disconnect XXX.XXX.194.238$./adb connect XXX.XXX.194.238

Note: Wi-Fi may not be available in some network environments, and you need to connect to them using a network cable. It is best to disable the simulator so that only one device exists in the devices list.

2. sqlite3 operation

When the following operations are performed, only one device is allowed in the Database List. Otherwise, an error is returned. The disconnect command can be used to disconnect the POs server. If the simulator is disconnected, it is directly disabled.

Use the following operations to open and access the database:

$./adb shell$cd sdcard/path/subdir$sqlite3 dsxniubility.db

Generally, you can query and delete databases in the terminal. These two cases are described here.

$. Table // view the table list $. dump a table // view the data in the table $. schema a table // view the table structure $ rm A table // Delete

When the select statement is used for display, the default style is not clear. We recommend that you set it to a clear style. The specific style is no longer nonsense, just give it an optimal style.

$. Nullvalue null // null placeholder $. mode column // a relatively open style $. headers on // display the header $. width 5, 5 // decrease the table width to get more space $. show // view current settings

There is a pitfall when exiting, and the three Exit commands should be typed in appropriate scenarios

$. Exit; // exit $. exit in a statement // exit from the data table $ exit // exit from the database operation

 

Iii. Third-party Libraries

For third-party libraries, ORMLite and GreenDao are commonly used in Android. The former is easy to use and written based on the reflection principle, and its performance is inferior to that of the latter.

The greendao official website has a very obvious performance comparison chart, so I will write only greendao down.

GREENDAO is a third-party database management tool based on Android. Its Design Features

  • A streamlined library

  • Maximize performance

  • Minimize memory overhead

  • Easy-to-use APIs

  • Highly optimized for Android

1. greenDao Configuration

How to configure a project from scratch

①. Build. gradle

compile 'org.greenrobot:greendao:2.2.1'

②. Create a Module named similar to DaoGenerator

File → New → NewModule → java Library

③ Configure build. gradle for the newly created Module

apply plugin: 'java' task(run, dependsOn: 'classes', type: JavaExec) {    main = 'com.example.MainGen'    classpath = sourceSets.main.runtimeClasspath    systemProperty 'user.dir', project.rootDir} dependencies {    compile fileTree(dir: 'libs', include: ['*.jar'])    compile 'org.greenrobot:greendao-generator:2.2.0'     targetCompatibility = '1.7'    sourceCompatibility = '1.7'}

4. The MainGen mentioned above needs to create a class by yourself.

Implement a main function, and make some configuration

Public static void main (String [] args) throws Exception {// obtain some identifiers and set scheme String relativePath = System. getProperty ("user. dir "); int DB_VERSION = 201666; System. out. print ("dbVersion is:" + DB_VERSION); Schema schema = new Schema (DB_VERSION, "com. dsx. a201666 "); schema. enableActiveEntitiesByDefault (); schema. enableKeepSectionsByDefault (); // there may be many ways to create a data table: createMenuItem (schema); // specify and execute the code generation path String daoPath = relativePath + "/app/src/main/java"; File daoDir = new File (daoPath); if (! DaoDir. isDirectory () {// noinspection ResultOfMethodCallIgnored daoDir. mkdirs ();} new DaoGenerator (). generateAll (schema, daoPath );}

There are two special attributes to explain.

If enableActiveEntitiesByDefault is enabled, update, refresh, delete, and other operations between entity classes are supported. Therefore, this attribute is not enabled in general scenarios.

If enableKeepSectionsByDefault is enabled, you can customize data for the model. The following code is generated. Attributes written between the codes can be used but are not stored in data.

// KEEP INCLUDES - put your custom includes here// KEEP INCLUDES END // KEEP FIELDS - put your custom fields here// KEEP FIELDS END // KEEP METHODS - put your custom methods here// KEEP METHODS END

⑤ Right-click and execute the main function to generate various files (DaoMaster, DaoSession, entity and Dao of model classes)

You can also set preBuild. dependsOn in build. gradle so that it can be automatically executed during program compilation.

2. greenDao usage

First, create a database using the greenDao api in the MainGen file at the greenDao portal.

private static void createCategoryTable(Schema schema){    Entity entity = schema.addEntity("SnackCategory");    entity.implementsSerializable();    entity.addIntProperty("id").primaryKey().autoincrement();    entity.addIntProperty("no");    Property orderProperty = entity.addLongProperty("orderId").getProperty();    entity.addToOne(orderBase, orderProperty);    entity.addStringProperty("name");}

After the main function is called, The SnackCategory and SnackCategoryDao files are automatically generated. The former is equivalent to the entity class, and the latter is the operation layer. The Dao suffix file is used for read, load, insert, and other operations.

The difference between serializable and parcelable is that the former is used for saving to the local file database and network stream transmission. The latter is often used for memory transmission, with better performance.

 

GreenDao provides almost all functions of the api, which can be viewed in the header file. The basic operations are listed below.

// Delete the session. getSnackCategoryDao (). deleteAll (); // Save the session. getSnackCategoryDao (). insert (cate); session. getSnackCategoryDao (). insertInTx (cateList); // obtain List <SnackCategory> categoryList = session. getSnackCategoryDao (). loadAll ();

Obtain data according to certain requirements:

Retrieve items of all types of cold dishes and sort them by price

List <SnackFood> nicefoods = session. getSnackFoodDao (). queryBuilder (). where (SnackFoodDao. properties. categoryid. eq ("staple food ")). orderAsc (SnackFoodDao. properties. price ). list (); // Dong Boran blog

Take out all kinds of dishes with a price less than 10 yuan

QueryBuilder qb = session. getSnackFoodDao (). queryBuilder (); qb. where (SnackFoodDao. properties. categoryid. eq ("staple food"), SnackFoodDao. properties. price. le (10.0); List goodfoods = qb. list ();
Iv. Transaction Processing

Important and time-consuming operations need to be added to the transaction to avoid extreme problems.

SQLiteDatabase database = session.getDatabase();database.beginTransaction();try {    session.getSnackCategoryDao().deleteAll();    session.getSnackFoodDao().deleteAll();    session.getSnackCategoryDao().insertInTx(cateList);    session.getSnackFoodDao().insertInTx(snackList);    database.setTransactionSuccessful();} catch (Exception e) {    e.printStackTrace();} finally {    database.endTransaction();}

 

5. SD card permission and Path 1. Permission acquisition

The permission acquisition for this SD card is similar to the permission acquisition for other Android6.0 runtime operations, which are roughly divided into three operations: querying whether there is permission, requesting permission acquisition, and the callback method after the user selects

Query permission

Private boolean lackPermission () {return ContextCompat. checkSelfPermission (this, Manifest. permission. WRITE_EXTERNAL_STORAGE )! = PackageManager. PERMISSION_GRANTED | ContextCompat. checkSelfPermission (this, Manifest. permission. READ_PHONE_STATE )! = PackageManager. PERMISSION_GRANTED; // Dong borran blog Park}

Request permission

ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,        Manifest.permission.READ_PHONE_STATE}, WRITE_EXTERNAL_STORAGE_REQUEST_CODE);  

Callback Method for clicking after request

@ Overridepublic void onRequestPermissionsResult (int requestCode, String permissions [], int [] grantResults) {if (requestCode = mRequestCode (12) {if (grantResults. length> 0 & grantResults [0] = PackageManager. PERMISSION_GRANTED) {// authorization passed} else {// authorization Failed }}}}
2. The storage path determines that the SDK has the permission to be placed in the SD card. If you do not have the permission, the SDK will be placed in the root directory.
public DaoMaster.OpenHelper provideOpenHelper() {    File path = new File(Environment.getExternalStorageDirectory(), "path/subdir/" + DATABASE_NAME); path.getParentFile().mkdirs(); if (path.getParentFile().exists()) {        return new DaoOpenHelper(BaseApplication.application(), path.getAbsolutePath(), null);    } else {        return new DaoOpenHelper(BaseApplication.application(), DATABASE_NAME, null);    }}

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.