Easy to upgrade Android database by reflection method

Overview

Upgrade database of Android application is common task of developers. Each developer has each solution for this task. In this post, i will suggest a solution with reflection method. This solution help developer manage code easily.

How it work

onUpgrade method

    @Override
    public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion,
                          int newVersion) {
        try {
            Log.i(TAG, "upgrade: " + oldVersion + "--" + newVersion);
            if (oldVersion < newVersion) {
                for (int i = oldVersion; i < newVersion; i++) {
                    String methodName = "updateFromDatabaseVersion" + i;
                    Method method = getClass().getDeclaredMethod(methodName, null);
                    method.setAccessible(true);
                    method.invoke(this, null);
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "onUpgrade", e);
        }
    }

update method

    private void updateFromDatabaseVersion41() {
        try {
            // write your code here
        } catch (Exception e) {
            Log.e(TAG, "updateFromDatabaseVersion41", e);
        }
    }

In first code block, I use reflexion in below code:

String methodName = "updateFromDatabaseVersion" + i;
Method method = getClass().getDeclaredMethod(methodName, null);
method.setAccessible(true);
method.invoke(this, null);

This code will run update method (such ash 2nd code block) automatically.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s