还原会议室数据库后从备份文本文件中读取数据

Reading data from a backup text file after restoring room database

提问人:Anesu Mazvimavi 提问时间:10/4/2023 更新时间:10/4/2023 访问量:18

问:

我正在构建一个应用程序,用于在 Android Studio 中备份和恢复房间数据库。备份过程工作正常,但是当我尝试还原数据库(使用Recyclerview)时,它不会向我显示所有数据。我怀疑问题可能出在从文本文件中读取字符串。

这是我的方法

  public void restoreDatabase() throws IOException {
        File backupFile = new File(Environment.getExternalStorageDirectory(), AppDatabase.DATABASE_NAME + ".txt");

        if (!backupFile.exists()) {
            throw new FileNotFoundException("Backup file does not exist");
        }

        AppDatabase database = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, "InnBucks_DB").allowMainThreadQueries().build();
        UserDao userDao = database.userDao();

        try (FileInputStream inputStream = new FileInputStream(backupFile)) {
            byte[] buffer = new byte[1024];
            int bytesRead;

            while ((bytesRead = inputStream.read(buffer)) != -1) {
                String line = new String(buffer, 0, bytesRead);

                // Split the line into user data
                String[] userData = line.split(" ");

                // Create a new user object
                User user = new User();
                user.setId(Integer.parseInt(userData[0]));
                user.setUserId(userData[1]);
                user.setName(userData[2]);

                // Add the user to the database
                userDao.registerUser(user);
            }
        }

// Get the list of users from the database.
        List<User> userList = userDao.getallusers();

// Call the setUserList() method on the RecyclerView adapter to update the list of users.
        userListAdapter.setUserList(userList);

// Notify the RecyclerView adapter that the data has changed.
        userListAdapter.notifyDataSetChanged();

        Toast.makeText(this, "Database restored successfully", Toast.LENGTH_SHORT).show();
    }

这是我的数据库,在我单击删除然后还原之前enter image description here

当我恢复数据库时,这是输出,正如你所看到的,缺少数据enter image description here

java 字符串 拆分 android-room

评论

0赞 MikeT 10/5/2023
停止并重新启动应用程序,然后显示正确的数据吗?由于幕后SQLiteOpenHelper的潜在复杂性,您可能必须以某种方式清除所有基础实例,并且根据 stackoverflow.com/questions/44317525/,重新启动活动可能是解决方案...(例如)。

答: 暂无答案