android - 如何以及在何处关闭()我的数据库以停止获取 E/SQLiteLog : (283)

标签 android database sqlite android-sqlite android-room

当我在数据库浏览器中打开数据库文件时,它是空的。我得到这个 E/SQLiteLog:(283)从 WAL 文件中恢复了 16 帧。使用 Room 保存数据并在应用程序关闭时将其填充回去是否合适?如果有人能提供帮助,我会很高兴,谢谢。

/这是我在数据库类中的实例化/

public static synchronized NoteDataBase getInstance(Context context){

    if (instance == null) {
        instance = Room.databaseBuilder(context.getApplicationContext(),
                NoteDataBase.class , "note_database")
                .fallbackToDestructiveMigration()
                .build();
    }
    return instance;
}
} 
@Override
public void close() {
    super.close();
    instance = null;
}

public void backup(Context context) {
    instance.close();
    //......... backup the file
    getInstance(context);
}

/和我的存储库/

 public NoteRepository(Application application) {
    dataBase = NoteDataBase.getInstance(application);
    noteDao = dataBase.noteDao();
    allNotes = noteDao.getAllNotes();

/我的一些viewmodel/

public class NoteViewModel extends AndroidViewModel  {

public NoteViewModel(@NonNull Application application)  {
    super(application);
    repository = new NoteRepository(application);
    allNotes = repository.getAllNotes();
}

public void insert(Note note) {
    repository.insert(note);
}

/还有我保存一些结果的 fragment/

private void saveNote(){

    String savedscore = finalScore.getText().toString();
    ArrayList<String> daycheks =  new ArrayList<>();
    for (int i = 0; i < itemList.size(); i++) {
        daycheks.add(itemList.get(i).toString());
    }

    Note note = new Note(savedscore , daycheks);
    model.insert(note);

    Toast.makeText(getContext() , "Result saved" ,Toast.LENGTH_SHORT).show();

}

最佳答案

备份数据库时,您应该在备份之前完全检查数据库(关闭数据库是一种选择(最简单的))或备份 -wal-shm 文件以及实际的数据库文件。

  • -wal/-shm-journal 文件与数据库文件同名,并以相应的扩展名作为后缀。<

另一种选择是使用 setJournalMode 在日志模式下打开数据库.

  • WAL和Journal模式的区别是

    • 在 WAL 模式中,更改应用于 -wal 文件而不是数据库本身(尽管访问 -wal 文件就好像它是数据库的一部分一样数据库),然后回滚就是从 -wal 文件中删除相应的数据。

    • 在日志模式下,数据库发生更改并将这些更改写入-journal 文件,回滚会根据日志文件撤消更改。

      <
    • 参见 Write-Ahead Logging获取更全面的信息。

可以看出,如果您复制数据库时没有检查点数据库并且没有 -wal 文件,则数据可能会丢失。

例子

以下示例模拟备份数据库,包括在添加一些行后关闭数据库(但跳过实际备份)。请注意,为方便起见,这是在主线程上完成的。

数据库类:-

@androidx.room.Database(entities = MyTable.class,version = 1)
public abstract class NoteDataBase extends RoomDatabase {

    private static String DBNAME = "mydb";
    static NoteDataBase instance;

    abstract MyTableDao getMyTableDao();
    public static synchronized NoteDataBase getInstance(Context context) {
        if (instance == null) {
            instance = Room.databaseBuilder(context, NoteDataBase.class,DBNAME)
                    .fallbackToDestructiveMigration()
                    .allowMainThreadQueries()
                    .build();
        }
        return instance;
    }

    @Override
    public void close() {
        super.close();
        instance = null;
    }

    public void backup(Context context) {
        instance.close();
        //......... backup the file
        getInstance(context);
    }
}
  • 即基本上是你的类,但重要的是有一个备份方法,关闭数据库然后将实例变量设置为 null,在下次使用时有效地强制打开。

使用以上内容的 Activity :-

public class MainActivity extends AppCompatActivity {

    NoteDataBase mDB;
    MyTableDao mMyTableDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d("APPINFO","Retrieving the Database Instance");
        mDB = NoteDataBase.getInstance(this);
        Log.d("APPINFO","Retrieving the Database DAO");
        mMyTableDao = mDB.getMyTableDao();
        Log.d("APPINFO","Inserting Data (10 rows)");
        for (int i=1;i < 11; i++) {
            mMyTableDao.insertMyTableRow(new MyTable("MYVALUE" + i));
        }
        Log.d("APPINFO","Mock backup/close");
        mDB.backup(this);
        Log.d("APPINFO","Retrieveing the Database Instance after the close");
        mDB = NoteDataBase.getInstance(this);
        Log.d("APPINFO","Retrieving Rows from the Database");
        for(MyTable m: mDB.getMyTableDao().getAllMyTableRows()) {
            Log.d("MYTABLEINFO","ID = " + m.getId() + " VALUE = " + m.getValue());
        }
        Log.d("APPINFO","Closing the database");
        mDB.close();
        MyTable m = mDB.getMyTableDao().getMyTableRowById(1L);
        Log.d("MYTABLEINFO","ID = " + m.getId() + " VALUE = " + m.getValue());
    }
}

结果(日志):-

2019-10-21 15:47:58.689 16269-16269/? D/APPINFO: Retrieving the Database Instance
2019-10-21 15:47:58.699 16269-16269/? D/APPINFO: Retrieving the Database DAO
2019-10-21 15:47:58.701 16269-16269/? D/APPINFO: Inserting Data (10 rows)
2019-10-21 15:47:58.743 16269-16269/? D/APPINFO: Mock backup/close
2019-10-21 15:47:58.752 16269-16269/? D/APPINFO: Retrieveing the Database Instance after the close
2019-10-21 15:47:58.752 16269-16269/? D/APPINFO: Retrieving Rows from the Database
2019-10-21 15:47:58.773 16269-16269/? D/MYTABLEINFO: ID = 1 VALUE = MYVALUE1
2019-10-21 15:47:58.773 16269-16269/? D/MYTABLEINFO: ID = 2 VALUE = MYVALUE2
2019-10-21 15:47:58.773 16269-16269/? D/MYTABLEINFO: ID = 3 VALUE = MYVALUE3
2019-10-21 15:47:58.773 16269-16269/? D/MYTABLEINFO: ID = 4 VALUE = MYVALUE4
2019-10-21 15:47:58.773 16269-16269/? D/MYTABLEINFO: ID = 5 VALUE = MYVALUE5
2019-10-21 15:47:58.773 16269-16269/? D/MYTABLEINFO: ID = 6 VALUE = MYVALUE6
2019-10-21 15:47:58.773 16269-16269/? D/MYTABLEINFO: ID = 7 VALUE = MYVALUE7
2019-10-21 15:47:58.773 16269-16269/? D/MYTABLEINFO: ID = 8 VALUE = MYVALUE8
2019-10-21 15:47:58.774 16269-16269/? D/MYTABLEINFO: ID = 9 VALUE = MYVALUE9
2019-10-21 15:47:58.774 16269-16269/? D/MYTABLEINFO: ID = 10 VALUE = MYVALUE10
2019-10-21 15:47:58.774 16269-16269/? D/APPINFO: Closing the database
2019-10-21 15:47:58.784 16269-16269/? E/ROOM: Invalidation tracker is initialized twice :/.
2019-10-21 15:47:58.784 16269-16269/? D/MYTABLEINFO: ID = 1 VALUE = MYVALUE1
  • 注意最后一行,这是因为使用了旧实例而不是获取新实例(实际上应该使用 mDB = NoteDataBase.getInstance(this);)

值得注意的是,在运行上面的命令之后,数据库有一个空的 -wal 文件:-

enter image description here

  • 因此数据库已完全检查点。

从设备资源管理器复制此文件并在 SQLite 工具 (Navicat) 中打开显示:-

enter image description here

  • 即插入的数据存在,room_master_table 和 android_metadata 表也是如此

替代关闭

关闭数据库的替代方法是使用 PRAGMA wal_checkpoint(?)

如果数据库类包含以下方法:-

public void checkpoint() {
    int attempts = 0;
    int max_attempts = 10;
    Cursor csr;
    SupportSQLiteDatabase ssd  = instance.getOpenHelper().getWritableDatabase();
    if (isWALOn(ssd)) {
        Log.d("CHKPOINTINFO","Attempt " +  (attempts + 1));
        while (checkpoint(ssd) > 0 && attempts++ < max_attempts) { }
    }
}

private boolean isWALOn(SupportSQLiteDatabase db) {
    boolean rv = false;
    Cursor csr = db.query("PRAGMA journal_mode");
    if  (csr.moveToFirst()) {
        if (csr.getString(0).toLowerCase().equals("wal")) rv = true;
    }
    csr.close();
    return rv;
}

private int checkpoint(SupportSQLiteDatabase db) {
    Log.d("CHKPOINTINFO","Attempting Database Ceckpoint");
    int blocked = 0;
    int pages_to_checkpoint = 0;
    int checkpointed_pages = 0;
    Cursor csr = db.query("PRAGMA wal_checkpoint(TRUNCATE)");
    if (csr.moveToFirst()) {
        blocked = csr.getInt(0);
        pages_to_checkpoint = csr.getInt(1);
        checkpointed_pages = csr.getInt(2);
    }
    csr.close();
    Log.d("CHKPOINTINFO",
            "Checkpoint values Blocked = " + blocked +
                    " Pages to Checkpoint = " + pages_to_checkpoint +
                    " Pages Checkpointed = " + checkpointed_pages
    );
    if (blocked > 0) return -1;
    if (checkpointed_pages < pages_to_checkpoint) return 1;
    return 0;
}
  • 注意为测试添加的日志记录,通常这会被删除。

可以使用mDB.backup(),而不是mDB.checkpoint()。这样做的好处是数据库保持打开状态。

关于android - 如何以及在何处关闭()我的数据库以停止获取 E/SQLiteLog : (283),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58474490/

相关文章:

Mysql 与 MongoDB 和 DynamoDB - 用户跟踪项目

.net - LocalDatabase-短期还是长期连接?

java - 如何将 "propagate"将一个 `ArrayList<String>` 排序到另一个?

android - 无法从 Android 设备连接到谷歌云端点

php - 找不到类 'Db'

mysql - 如何编写此 MySQL 查询? (约会时间)

android - 我应该保留远程数据库的本地副本吗?

java - SQLite - 检查时间是否超过一个月前

android - 为什么 Android SDK Manager 只显示默认包?

java - 滑动时的 Android ViewPager Bug