Android Program Development: (19) database -- 19.1 create database auxiliary class

Source: Internet
Author: User
Tags sqlite database

Currently, the method described is only used to store some simple data. If you want to store relational data, you can use the database more efficiently. For example, you need to store the scores of each student in the school. In this case, you are best to use a database because you can query the scores of a student. Moreover, the use of databases can maintain the integrity of the relationships between different data.

Android uses the SQLite database system. With this database, only the program that creates it can use it, and other programs cannot access it.

The following sections describe how to create an SQLite database in your program by encoding. For Android, the storage location of the database created by encoding is/data/<packane_name>

/Databases.

A good way to process a database is to create a database helper class that encapsulates all data operations. Therefore, this section describes how to create a database auxiliary class dbadapter, which contains creating, opening, closing, and using the SQLite database.

Let's create a database named mydb. It contains a table named contacts, which has three columns: _ id, name, and email.

1. Create a project, databases.

2. Create a class, dbadater.

3. Code in dbadapter. java.

public class DBAdapter {    static final String KEY_ROWID = "_id";    static final String KEY_NAME = "name";    static final String KEY_EMAIL = "email";    static final String TAG = "DBAdapter";    static final String DATABASE_NAME = "MyDB";    static final String DATABASE_TABLE = "contacts";    static final int DATABASE_VERSION = 2;    static final String DATABASE_CREATE =        "create table contacts (_id integer primary key autoincrement, "        + "name text not null, email text not null);";    final Context context;    DatabaseHelper DBHelper;    SQLiteDatabase db;        public DBAdapter(Context ctx)    {        this.context = ctx;        DBHelper = new DatabaseHelper(context);    }    private static class DatabaseHelper extends SQLiteOpenHelper    {        DatabaseHelper(Context context)        {            super(context, DATABASE_NAME, null, DATABASE_VERSION);        }        @Override        public void onCreate(SQLiteDatabase db)        {            try {                db.execSQL(DATABASE_CREATE);            } catch (SQLException e) {                e.printStackTrace();            }        }        @Override        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)        {            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "                    + newVersion + ", which will destroy all old data");            db.execSQL("DROP TABLE IF EXISTS contacts");            onCreate(db);        }    }    //---opens the database---    public DBAdapter open() throws SQLException     {        db = DBHelper.getWritableDatabase();        return this;    }    //---closes the database---    public void close()     {        DBHelper.close();    }    //---insert a contact into the database---    public long insertContact(String name, String email)     {        ContentValues initialValues = new ContentValues();        initialValues.put(KEY_NAME, name);        initialValues.put(KEY_EMAIL, email);        return db.insert(DATABASE_TABLE, null, initialValues);    }    //---deletes a particular contact---    public boolean deleteContact(long rowId)     {        return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;    }    //---retrieves all the contacts---    public Cursor getAllContacts()    {        return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME,                KEY_EMAIL}, null, null, null, null, null);    }    //---retrieves a particular contact---    public Cursor getContact(long rowId) throws SQLException     {        Cursor mCursor =                db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,                KEY_NAME, KEY_EMAIL}, KEY_ROWID + "=" + rowId, null,                null, null, null, null);        if (mCursor != null) {            mCursor.moveToFirst();        }        return mCursor;    }    //---updates a contact---    public boolean updateContact(long rowId, String name, String email)     {        ContentValues args = new ContentValues();        args.put(KEY_NAME, name);        args.put(KEY_EMAIL, email);        return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;    }}

First, declare some constants that contain the fields required in some tables.

    static final String KEY_ROWID = "_id";    static final String KEY_NAME = "name";    static final String KEY_EMAIL = "email";    static final String TAG = "DBAdapter";    static final String DATABASE_NAME = "MyDB";    static final String DATABASE_TABLE = "contacts";    static final int DATABASE_VERSION = 2;    static final String DATABASE_CREATE =        "create table contacts (_id integer primary key autoincrement, "        + "name text not null, email text not null);";

In the dbadapter class, a private class is added. This class inherits the sqliteopenhelper class, which creates a database and implements Version Control for the database. Generally, the oncreate () and onupgrade () methods are rewritten as follows:

private static class DatabaseHelper extends SQLiteOpenHelper    {        DatabaseHelper(Context context)        {            super(context, DATABASE_NAME, null, DATABASE_VERSION);        }        @Override        public void onCreate(SQLiteDatabase db)        {            try {                db.execSQL(DATABASE_CREATE);            } catch (SQLException e) {                e.printStackTrace();            }        }        @Override        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)        {            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "                    + newVersion + ", which will destroy all old data");            db.execSQL("DROP TABLE IF EXISTS contacts");            onCreate(db);        }    }

If the database does not exist, the oncreate () method will create a new database. The onupgrade () method is called when the database needs to be upgraded. To determine whether the database needs to be upgraded, You need to determine the database_version constant. The implementation in the onupgrade () method is simple, that is, to delete the table and recreate it.

Then, define some data operations, such as opening, closing, adding, deleting, querying, and modifying data.

    //---opens the database---    public DBAdapter open() throws SQLException     {        db = DBHelper.getWritableDatabase();        return this;    }    //---closes the database---    public void close()     {        DBHelper.close();    }    //---insert a contact into the database---    public long insertContact(String name, String email)     {        ContentValues initialValues = new ContentValues();        initialValues.put(KEY_NAME, name);        initialValues.put(KEY_EMAIL, email);        return db.insert(DATABASE_TABLE, null, initialValues);    }    //---deletes a particular contact---    public boolean deleteContact(long rowId)     {        return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;    }    //---retrieves all the contacts---    public Cursor getAllContacts()    {        return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME,                KEY_EMAIL}, null, null, null, null, null);    }    //---retrieves a particular contact---    public Cursor getContact(long rowId) throws SQLException     {        Cursor mCursor =                db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,                KEY_NAME, KEY_EMAIL}, KEY_ROWID + "=" + rowId, null,                null, null, null, null);        if (mCursor != null) {            mCursor.moveToFirst();        }        return mCursor;    }    //---updates a contact---    public boolean updateContact(long rowId, String name, String email)     {        ContentValues args = new ContentValues();        args.put(KEY_NAME, name);        args.put(KEY_EMAIL, email);        return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;    }

Note: Android uses the cursor class as the returned result of data query. Think of curosr as a pointer to the query result. You can use cursor to increase query efficiency.

Use the contentvalurs object to store key-value pairs.

To create a database using the dbadapter class, you must create an instance of the dbadapter class:

    public DBAdapter(Context ctx)    {        this.context = ctx;        DBHelper = new DatabaseHelper(context);    }

The constructor also creates a dbhelpter class to create a database.

DatabaseHelper(Context context)        {            super(context, DATABASE_NAME, null, DATABASE_VERSION);        }

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.