[Android] learn to use SQLite for data persistence combat pen

Before a period of time, do a simple memorandum of APP actual projects, the first time I used the SQLite for data persistence, I am here to share some understanding to you also remind myself, but also in order to consolidate their own knowledge

 

First, why should the data persistence

 

Like memorandum, we hope that every time you open after closing APP, we wrote in the APP can be stored in something down rather than be lost with the closure of APP somewhat similar, we want the data stored in external memory instead of hard disk the feeling

 

Second, the need to use the simple use SQLIte defined class or

 

1, the data model: to save the database read from or writing data in the database
Memorandum, for example, the data model is
Each memo id

Each memo content (content)

The importance of each memorandum (1 important, unimportant 0)

 

2, a database proxy class: for the simple conversion of a call from the calling to the APP API SQLite database
Corresponds to the basic operation of the database encapsulated to make it easy to use

 

3, CursorAdapter classes: the class to inherit an abstract manner Android standard data access process
My understanding is that it provides data PP in control of a bridge between the acquisition and the acquisition of data in the database

 


Third, code implementation, in order to combat this practice I was project as an example

 

The first is the data model
Omitted getter and setter method for each member variable

 

public class Reminder {
    private int mId;
    private String mContent;
    private int mImportent;
    public Reminder(int id, String content, int importent) {
        mId = id;
        mContent = content;
        mImportent = importent;
    }

 


Then the database proxy class RemindersDbAdapter

 

The first is the definition of a database of some constants, such as the library name, table name, version number, etc.

   public static Final String COL_ID = "_id" ; public static Final String COL_CONTENT = "Content" ; public static Final String COL_IMPORTENT = "importent" ; // field name indexing public static Final int index_id = 0 ; public static Final int INDEX_CONTENT = index_id . 1 + ; public static Final int INDEX_IMPORTENT index_id + = 2 ; // for TAG log public static Final String TAG = "RemindersDbAdapter" ; // two database API objects, the former for opening and closing the database, is a helper class Private DatabaseHelper mDbHelper; Private SQLiteDatabase the MDB; // library name, table name, version name public static Final String = DATABASE_NAME "dba_remdrs" ; public static Final String TABLE_NAME = "tbl_remdrs" ; public static Final int database_version = 1 ; // context object provides access to the Android system Private Final context mCtx; // SQL statements to create the database public static final String DATABASE_CREATE = "CREATE TABLE if not exists " + TABLE_NAME + " ( " + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COL_CONTENT + " TEXT, " + COL_IMPORTENT + " INTEGER );";

 

Description of the SQL statement

General CREATE statement does if not exists, if not in this error will join if not exists then the second run APP, because the same show is trying to create a new table, and then add the phrase to show only a warning, prompt you to the table already exists, without error

Another parameter is  INTEGER PRIMARY KEY AUTOINCREMENT, because in SQLite, he will add a rowid for each table, this can be used as a hidden field, and because the rowid of each row is unique, so you can take id as the primary key,  a field data type specified as COL_ID INTEGER pRIMARY kEY AUTOINCREMENT, said INTEGER pRIMARY kEY AUTOINCREMENT alias for the rowid, when inserting data, only need to specify the value of the field is null, it will be absorbed by engine automatically set value

Further TEXT data type statement in SQLite refers to a combination of text, or text and numbers, up to 2 ^ 16 characters (Access is 255 characters)


Open and close the database

//    open
    public void open() throws SQLException{

        mDbHelper = new DatabaseHelper(mCtx);

        mDb = mDbHelper.getWritableDatabase();

    }

//    close

    public void  close(){

        if (mDbHelper != null){

            mDbHelper.close();

        }

    }

 


Then about CURD (create, read, update, delete) operations to achieve

 

// be written by the database data directly 

    public  void createReminder (String name, Boolean importent) { 

        ContentValues values = new new ContentValues (); 

        values.put (COL_CONTENT, name); 

        values.put (COL_IMPORTENT, importent); 

        mDb.insert ( TABLE_NAME, null , values); 

    } 

// writing is performed by the data model 
    public  Long createReminder (Reminder Reminder) { 

        ContentValues values = new new ContentValues (); 

        values.put (COL_CONTENT, reminder.getContent ()); // Business Card name

        values.put(COL_IMPORTENT,reminder.getImportent());//Contact Phone Number

//        inseting row

        return mDb.insert(TABLE_NAME,null,values);

    }

// 从数据库读取内容

    public Reminder fetchReminderById(int id){

        Cursor cursor = mDb.query(TABLE_NAME,new String[]{COL_ID,

                COL_CONTENT,COL_IMPORTENT},COL_ID + "=?",

                new String[]{String.valueOf(id)},null,null,null,null);

        if (cursor != null)

            cursor.moveToFirst();

        return new Reminder(

                cursor.getInt(INDEX_ID),

                cursor.getString(INDEX_CONTENT),

                cursor.getInt(INDEX_IMPORTENT));

    }

    public Cursor fetchAllReminders(){

        Cursor mCursor = mDb.query(TABLE_NAME,new String[]{COL_ID,

                        COL_CONTENT,COL_IMPORTENT},

                        null,null,null,null,null);

        if (mCursor != null){

            mCursor.moveToFirst();

        }

        return mCursor;

    }

//    更新数据库

    public void updataReminder(Reminder reminder){

        ContentValues values = new ContentValues();

        values.put(COL_CONTENT,reminder.getContent());

        values.put(COL_IMPORTENT,reminder.getImportent());

        mDb.update(TABLE_NAME,values,

                COL_ID +"=?",new String[]{String.valueOf(reminder.getId())});

    }

//删除数据

    public void deleteReminderById(int nId){

        mDb.delete(TABLE_NAME,COL_ID + "=?",new String[]{String.valueOf(nId)});

    }

    public void deleteAllReminders(){

        mDb.delete(TABLE_NAME,null,null);

    }

 

Description of the ContentValues

It is a shuttle data, similar to a hash table, key-value pairs are stored, but ContentValues of type String Key, and Value was basic types (int, etc.), through its put () to put the key to

about the Cursor
the Cursor each row is a collection, which uses moveToFirst () to locate the first row, the need to use a database query when defining the function, the multi-bit function parameters

type of data Parameter name effect
Boolean distinct It is true, that every piece of data is unique, and vice versa
String table Table Name
String[] columns To return the name of the array (field name) column, return all columns is null
String selection Screening for the line, similar to the SQL WHERE
String[] selectionArg The selection appears for replacement?
String groupby Grouping the set return line, a null packet is not
String having Cursor determine which rows are placed in the filter (not get to know)
String orderby Sort, the default sort is null press
String limit Limit the number of rows returned
CancellationSignal cancellationsignal When the signal to cancel the operation, was not null, there will be thrown in the cancellation operationCanceledException

Which a total of four different query function parameters, 10 parameters include all of the above parameters, nine parameter is not included cancellationsignal, 8 argument does not contain a distinct and cancellationsignal, 7 argument does not contain a distinct, limit and cancellationsignal
I feel As long as the query function appreciated that the code is on the CRUD operations it is very easy to understand


CursorAdapter class
this part I still need to digest what in many subsequent updates

Guess you like

Origin www.cnblogs.com/Ringky/p/12446616.html