getReadableDatebase() 和getwriteableDatebase()的解读

 
 

 
 

1. 两个方法干嘛的?

两个方法都是用于获取数据库的读写对象,并不是字面上一个获取读取数据库的对象,另一个获取写

数据库的对象。

2. getWritableDatabase()

源码注释:

/**
 * Create and/or open a database that will be used for reading and writing.
 * The first time this is called, the database will be opened and
 * {@link #onCreate}, {@link #onUpgrade} and/or {@link #onOpen} will be
 * called.
 *
 * <p>Once opened successfully, the database is cached, so you can
 * call this method every time you need to write to the database.
 * (Make sure to call {@link #close} when you no longer need the database.)
 * Errors such as bad permissions or a full disk may cause this method
 * to fail, but future attempts may succeed if the problem is fixed.</p>
 *
 * <p class="caution">Database upgrade may take a long time, you
 * should not call this method from the application main thread, including
 * from {@link android.content.ContentProvider#onCreate ContentProvider.onCreate()}.
 *
 * @throws SQLiteException if the database cannot be opened for writing
 * @return a read/write database object valid until {@link #close} is called
 */
public SQLiteDatabase getWritableDatabase() {
    synchronized (this) {
        return getDatabaseLocked(true);
    }
}

  • 它会调用并返回一个可以读写数据库的对象
  • 在第一次调用时会调用onCreate的方法
  • 当数据库存在时会调用onOpen方法
  • 结束时调用onClose方法

3. getReadableDatabase()

源码注释:

/**
 * Create and/or open a database.  This will be the same object returned by
 * {@link #getWritableDatabase} unless some problem, such as a full disk,
 * requires the database to be opened read-only.  In that case, a read-only
 * database object will be returned.  If the problem is fixed, a future call
 * to {@link #getWritableDatabase} may succeed, in which case the read-only
 * database object will be closed and the read/write object will be returned
 * in the future.
 *
 * <p class="caution">Like {@link #getWritableDatabase}, this method may
 * take a long time to return, so you should not call it from the
 * application main thread, including from
 * {@link android.content.ContentProvider#onCreate ContentProvider.onCreate()}.
 *
 * @throws SQLiteException if the database cannot be opened
 * @return a database object valid until {@link #getWritableDatabase}
 *     or {@link #close} is called.
 */
public SQLiteDatabase getReadableDatabase() {
    synchronized (this) {
        return getDatabaseLocked(false);
    }
}
  • 它会调用并返回一个可以读写数据库的对象
  • 在第一次调用时会调用onCreate的方法
  • 当数据库存在时会调用onOpen方法
  • 结束时调用onClose方法

4. 区别

是不是上面两个总结一样?
然后事实呢?

  1. 两个方法都是返回读写数据库的对象,但是当磁盘已经满了时,getWritableDatabase会抛异常,而getReadableDatabase不会报错,它此时不会返回读写数据库的对象,而是仅仅返回一个读数据库的对象。
  2. getReadableDatabase会在问题修复后继续返回一个读写的数据库对象。
  3. 两者都是数据库操作,可能存在延迟等待,所以尽量不要在主线程中调用。

猜你喜欢

转载自blog.csdn.net/u011414643/article/details/78805429