提问人:Anesu Mazvimavi 提问时间:10/4/2023 更新时间:10/4/2023 访问量:18
还原会议室数据库后从备份文本文件中读取数据
Reading data from a backup text file after restoring room database
问:
我正在构建一个应用程序,用于在 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();
}
答: 暂无答案
评论