[Android] Database trong Android – P4 Update database

The main purpose of the tutorial is all Database in Android today – Update the database how to apply is not lost, not faulty when you want to change the database.

League history after done app Notes, you want your notes with last modification time. So we turn to go perform alone.

update database android

Step 1: Class structure changes Note

Each note should have more time for final amendments, so we need to add attributes to the class Note lastModified.

package cachhoc.net.tut.demodatabase;

public class Note {
    private long id;
    private String title;
    private String content;
    private String lastModified;

    /**
    * here is getter and setter of id, title, content.
    */

    public String getLastModified() {
        return lastModified;
    }

    public Note setLastModified(String lastModified) {
        this.lastModified = lastModified;
        return this;
    }
}

We just need to show time last modified but need not calculate what it should be used with String without using type date (date type that will be more difficult to handle).

Step 2: Update DatabaseHelper

This is the most important step. we in turn change the following part of DatabaseHelper:

Changing the command table creation

First we need to add one constant is the title of a new column. Then add it to the command create table notes

/**
 * table note contain id, title, content
 */
public static final String TABLE_NOTE = "tb_note";
public static final String KEY_ID_NOTE = "id";
public static final String KEY_TITLE_NOTE = "title";
public static final String KEY_CONTENT_NOTE = "content";
public static final String KEY_LAST_MODIFIED_NOTE = "last_modified";

/**
 * string for create table note
 */
public static final String CREATE_TABLE_NOTE =
        "CREATE TABLE " + TABLE_NOTE + "(" +
                KEY_ID_NOTE + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL" +
                ", " + KEY_TITLE_NOTE + " TEXT NOT NULL" +
                "," + KEY_CONTENT_NOTE + " TEXT NOT NULL" +
                "," + KEY_LAST_MODIFIED_NOTE + " TEXT DEFAULT \'\'" +
                ")";

This ensures the new phone will also be installed in table columns last_modified note.

Update database version

You remember the other day we had 1 variable is DATA_VERSION, it was the version database. Now you growing it to greater than previous versions (last time was 1, hours should be increased to 2).

/**
 * value for update database
 */
public static final int DATA_VERSION = 2;

Perform database update

As I had mentioned the day before onUpgrade method will be called when we update the database version. Just DATA_VERSION change, this method will be called. we rewrite this method are as follows:

/**
 * call when change DATA_VERSION
 * help we update database
 */
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // update database for database version < 2
    if (oldVersion < 2) {
        db.execSQL("ALTER TABLE " + TABLE_NOTE + " ADD COLUMN " + KEY_LAST_MODIFIED_NOTE + " TEXT DEFAULT \'\'");
    }
}

Have you noticed the following points:

  • Khi update app, the system will automatically save the database version of the old version in the above variables oldVersion. newversion is new DATA_VERSION.

  • Some of you often cleared the tables and callback function in this onCreate, however so will void the entire old data. This is loath to do it, if they avoid any avoid.

  • His condition using oldVersion < 2 to perform edit table. This enables you to edit the database in stages. For example the next time DATA_VERSION = 3 then you add an if statement(oldVersion < 3) and implementation. It helps you to remember the phase update the database and also enables the app update intervals (eg from 1.0 not up 2.0 but up 3.0 right) no update errors.

  • This field last_modified themselves to default is empty string, Help the records had not been null, avoid error retrieving.

Update the related retrieval method

In this section, we need to revise 2 methods take note and take notes on ContentValues ​​from the database to be able to put in and take out enough information.

/**
 * convert note to contentvalues
 * don't put id of note because
 * when insert id will auto create
 * when update we don't update id
 */
private ContentValues noteToValues(Note note) {
    ContentValues values = new ContentValues();
    values.put(KEY_TITLE_NOTE, note.getTitle());
    values.put(KEY_CONTENT_NOTE, note.getContent());
    values.put(KEY_LAST_MODIFIED_NOTE, note.getLastModified());
    return values;
}

/**
 * convert cursor to note
 */
private Note cursorToNote(Cursor cursor) {
    Note note = new Note();
    note.setId(cursor.getInt(cursor.getColumnIndex(KEY_ID_NOTE)))
            .setTitle(cursor.getString(cursor.getColumnIndex(KEY_TITLE_NOTE)))
            .setContent(cursor.getString(cursor.getColumnIndex(KEY_CONTENT_NOTE)))
            .setLastModified(cursor.getString(cursor.getColumnIndex(KEY_LAST_MODIFIED_NOTE)));
    return note;
}

Step 3: Update where new data creation

Listen seem a bit confusing but it is simple, is the correct method in class NoteAcitivty save to save time updating note.

/**
 * get title and content and update last modified time of note, if they empty then finish
 * if they not empty then check note is null?
 * if note is null (create new note), we will create note and insert into database
 * if note not null then we update note
 * after save we finish activity
 */
private void save() {

    String title = editTitle.getText().toString().trim();
    String content = editContent.getText().toString().trim();

    String notify = null;

    if (TextUtils.isEmpty(title) && TextUtils.isEmpty(content)) {
        notify = "note empty, don't save!";
    } else {

        // get curren time for last modified
        SimpleDateFormat formatTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar cal = Calendar.getInstance();
        String currenTime = formatTime.format(cal.getTime());

        // new note
        if (note == null) {
            Note note = new Note();
            note.setTitle(title).setContent(content).setLastModified(currenTime);
            if (db.insertNote(note) > 0) {
                notify = "add success!";
            } else {
                notify = "add fail!";
            }
        } else { // update note
            note.setTitle(title).setContent(content).setLastModified(currenTime);
            if (db.updateNote(note)) {
                notify = "update success!";
            } else {
                notify = "update fail!";
            }
        }
    }

    Toast.makeText(context, notify, Toast.LENGTH_SHORT).show();
    finish();
}

Step 4: Update Interface

After making edits in the database file, we return edit interface accordingly.

Each item will now display more 1 School is in the bottom left last_modified.

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:layout_margin="3dp"
    card_view:cardCornerRadius="1dp">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:id="@+id/item_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/backgroud_item_note"
        android:gravity="center_vertical"
        android:orientation="vertical"
        android:padding="5dp">

        <TextView
            android:id="@+id/tv_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:gravity="center_vertical"
            android:lines="1"
            android:text="@string/title_note"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/tv_content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:gravity="center_vertical"
            android:lines="1"
            android:text="@string/content"
            android:textSize="13sp" />

        <TextView
            android:id="@+id/tv_last_modified"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="end"
            android:gravity="end"
            android:textSize="13sp" />
    </LinearLayout>

</android.support.v7.widget.CardView>

Finally accordingly revised severance Adapter. We just need to fix 2 place the class RecyclerViewHolder in ItemNoteAdapter and methods onBindViewHolder

/**
 * ViewHolder for item view of list
 */

public class RecyclerViewHolder extends RecyclerView.ViewHolder implements
        OnClickListener {

    public LinearLayout container;
    public TextView tvTitle;
    public TextView tvContent;
    public TextView tvLastModified; //add

    public RecyclerViewHolder(View itemView) {
        super(itemView);

        container = (LinearLayout) itemView.findViewById(R.id.item_container);
        tvTitle = (TextView) itemView.findViewById(R.id.tv_title);
        tvContent = (TextView) itemView.findViewById(R.id.tv_content);
        tvLastModified = (TextView) itemView.findViewById(R.id.tv_last_modified);

        container.setOnClickListener(this);
    }

    // click item then display note
    @Override
    public void onClick(View v) {
        MainActivity.showNote(context, list.get(getPosition()).getId());
    }
}
/**
 * set data for item
 */
@Override
public void onBindViewHolder(RecyclerViewHolder viewHolder, int position) {
    Note note = list.get(position);
    viewHolder.tvTitle.setText(note.getTitle());
    viewHolder.tvContent.setText(note.getContent());
    viewHolder.tvLastModified.setText(note.getLastModified());
}

Fasteners are the most important post has finished. The next section I will guide you how to back up data to a memory card.

Posts made in the tutorial Database trong Android by nguyenvanquan7826