你好,我正在开发Android应用程序。它目前有9个表格,我已经创建了一个实例来打开数据库,并在整个项目中使用相同的实例。我不知道这是否会导致我的UI冻结。我应该在每次进行数据库操作时打开和关闭数据库吗?还是我现在的做法是正确的?
\** to fetch records**\
public synchronized SQLiteDatabase readDatabase() {
if(mOpenCounter == 1) {//to open the database only one time
// Reading
mDatabase = mDatabaseHelper.getReadableDatabase();
}
return mDatabase;
}
\** to open db **\
public synchronized SQLiteDatabase openDatabase()throws SQLException {
mOpenCounter+=1;
if(mOpenCounter == 1) {//to open the database only one tim
mDatabase = mDatabaseHelper.getWritableDatabase();
}
return mDatabase;
}
更新:我已经花了两天时间在这个问题上。在Google上查看了几个链接后,我发现我们需要在单独的线程上进行数据库操作。有人能给我一个如何做到这一点的例子吗?不是像一个查询那样,我有9个表,每个表大约有8个查询。每个查询都应该在单独的线程中运行吗?我的代码结构是这样的,我为每个表查询创建了一个单独的类,例如对于表A,所有关于这个表的查询都在TableAqueries这里。请给我一个在单独的线程中运行数据库操作的解决方案。请帮助我。
CursorLoader
与ContentProvider
配合使用,而不是直接与 SQLite 数据库配合使用。CursorLoader
没有doInBackground()
方法。一些数据库访问层(例如 Room)提供后台查询。除此之外,您可以使用 RxJava、普通的Thread
、AsyncTask
和无数其他线程选项。 - CommonsWare