在SQLite中需要API16方法的包装器

时间:2012-08-10 09:57:59

标签: android sqlite wrapper

使用API​​16,在Androids SQLiteDatabase类中引入了新的WAL(Write Ahead Logging)。我想测试是否为SQLite数据库启用了WAL。该应用程序也在较旧的Android版本上运行,因此我需要在SQLiteDatabase中为这些新函数提供包装类。功能是:

  • public boolean isWriteAheadLoggingEnabled()
  • public boolean enableWriteAheadLogging()
  • public void disableWriteAheadLogging()

Android Developer Blog我找到了一篇包装新类的包装类的文章。我没有找到的是现有类中新方法的包装器。我该怎么做?

1 个答案:

答案 0 :(得分:1)

SQLiteDatabase的构造函数是私有的,因此您无法扩展它并为类本身添加“包装器”。但是你可以像这样编写一个“帮助器”包装器:

public class WALWrapper {
    private boolean mAvailable;
    private Method mIsWriteAheadLoggingEnabled;
    private Method mEnableWriteAheadLogging;
    private Method mDisableWriteAheadLogging;
    private final SQLiteDatabase mDb;

    public WALWrapper(SQLiteDatabase db) {
        mDb = db;
        mAvailable = false;
        try {
            mIsWriteAheadLoggingEnabled =
                    SQLiteDatabase.class.getMethod("isWriteAheadLoggingEnabled");
            mEnableWriteAheadLogging =
                    SQLiteDatabase.class.getMethod("enableWriteAheadLogging");
            mDisableWriteAheadLogging =
                    SQLiteDatabase.class.getMethod("disableWriteAheadLogging");
            mAvailable = true;
        } catch (NoSuchMethodException e) {
        }
    }

    /**
     * Returns <code>true</code> if the {@link #isWriteAheadLoggingEnabled()},
     * {@link #enableWriteAheadLogging()} and {@link #disableWriteAheadLogging()}
     * are available.
     * @return <code>true</code> if the WALWrapper is functional, <code>false</code>
     *  otherwise.
     */
    public boolean isWALAvailable() {
        return mAvailable;
    }

    public boolean isWriteAheadLoggingEnabled() {
        boolean result = false;
        if (mIsWriteAheadLoggingEnabled != null) {
            try {
                result = (Boolean) mIsWriteAheadLoggingEnabled.invoke(mDb);
            } catch (IllegalArgumentException e) {
            } catch (IllegalAccessException e) {
            } catch (InvocationTargetException e) {
            }
        }
        return result;
    }

    public boolean enableWriteAheadLogging() {
        boolean result = false;
        if (mEnableWriteAheadLogging != null) {
            try {
                result = (Boolean) mEnableWriteAheadLogging.invoke(mDb);
            } catch (IllegalArgumentException e) {
            } catch (IllegalAccessException e) {
            } catch (InvocationTargetException e) {
            }
        }
        return result;
    }

    public void disableWriteAheadLogging() {
        if (mDisableWriteAheadLogging != null) {
            try {
                mDisableWriteAheadLogging.invoke(mDb);
            } catch (IllegalArgumentException e) {
            } catch (IllegalAccessException e) {
            } catch (InvocationTargetException e) {
            }
        }
    }
}