gpt4 book ai didi

java - 为什么Room数据库在重启应用后会丢失数据?

转载 作者:行者123 更新时间:2023-12-01 16:56:06 26 4
gpt4 key购买 nike

我正在将 Room Persistance 库与所有 Android 架构组件一起使用。在应用程序中,我有 3 个数据库,但问题出在只有一个。在我的 MainActivity 中,我有一个 RecyclerView,它显示 DatesDatabase 中的数据(日期)。单击每个元素时,将打开一个新 Activity 并显示引用特定日期的所有数据。 DAO 中的查询是:

@Query("SELECT * FROM Sorted WHERE date = :date")
LiveData<List<Sorted>> getSortedWhereDateIs(String date);

问题是,当我重新启动应用程序时,我仍然可以看到之前添加的日期,但没有引用该日期的数据。

重新启动之前: screenshot1 screenshot2

重启后: screenshot1 screenshot2

日期数据库代码:

@Database(entities = {Dates.class}, version = 2, exportSchema = false)
public abstract class DatesDatabase extends RoomDatabase {
private static DatesDatabase instance;

public abstract DatesDao datesDao();

public static synchronized DatesDatabase getInstance(Context context){
if (instance == null){
instance = Room.databaseBuilder(context.getApplicationContext(),
DatesDatabase.class, "dates_database").fallbackToDestructiveMigration()
.build();
}
return instance;
}
}

代码到数据库,不保存数据:

@Database(entities = {Sorted.class}, version = 3, exportSchema = false)
public abstract class SortedDatabase extends RoomDatabase {

private static SortedDatabase instanceSorted;

public abstract SortedDao sortedDao();

public static synchronized SortedDatabase getSortedInstance(Context context) {
if (instanceSorted == null) {
instanceSorted = Room.databaseBuilder(context.getApplicationContext(),
SortedDatabase.class, "unsorted_database").fallbackToDestructiveMigration().build();
}
return instanceSorted;
}
}

我尝试删除“fallbackToDestructiveMigration()”,但我有一个方法“deleteAll”,在这种情况下显示错误:

 viewModel.deleteAllDates();
viewModel.deleteAllUnsorted();
viewModel.deleteAllSorted();

以下是我如何将数据添加到 SortedDatabase(被删除):

 if (choosedMethod.equals("Eat a frog")) {
for (int i = 0; i < eatAFrogList.size(); i++){
Unsorted unsorted = eatAFrogList.get(i);
String name = unsorted.getName();
String date = unsorted.getDate();
int timeBegin = unsorted.getTimeBegin();
boolean attach = unsorted.isAttach();
int category = unsorted.getCategory();
int duration = unsorted.getDuration();
String categoryChart = unsorted.getCategoryChart();
Sorted sorted = new Sorted(name, timeBegin, duration, category, attach, date,
categoryChart);
viewModel1.insertSorted(sorted);
}

我通过算法对存储在 UnsortedDatabase 中的 Unsorted 类任务进行排序,然后将其添加到 SortedDatabase 中。

我的 recyclerview 适配器显示排序数据:

public class SortedAdapter extends RecyclerView.Adapter<SortedAdapter.SortedViewHolder> {

private List<Sorted> list = new ArrayList<>();

@NonNull
@Override
public SortedViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.tasks_layout , parent, false);
return new SortedAdapter.SortedViewHolder(itemView);
}

@Override
public void onBindViewHolder(@NonNull SortedViewHolder holder, int position) {
Sorted data = list.get(position);
holder.title.setText(data.getSortedName());
holder.date.setText(data.getSortedDate());
holder.category.setText(String.valueOf(data.getSortedCategory()));
holder.attach.setText(String.valueOf(data.isSortedAttach()));
holder.to.setText(String.valueOf(toTime(data.getSortedDuration() + data.getSortedTimeBegin())));
holder.from.setText(String.valueOf(toTime(data.getSortedTimeBegin())));
}

public void setSortedData(List<Sorted> sortedList){
this.list = sortedList;
notifyDataSetChanged();
}

@Override
public int getItemCount() {
return list.size();
}

class SortedViewHolder extends RecyclerView.ViewHolder{
private TextView title;
private TextView date;
private TextView from;
private TextView to;
private TextView category;
private TextView attach;

SortedViewHolder(@NonNull View itemView) {
super(itemView);
title = itemView.findViewById(R.id.tv_title);
date = itemView.findViewById(R.id.tv_date);
from = itemView.findViewById(R.id.tv_from2);
to = itemView.findViewById(R.id.tv_to2);
category = itemView.findViewById(R.id.tv_category);
attach = itemView.findViewById(R.id.tv_attach);
}
}
}

最后是显示数据的 Activity :

public class ShowSortedActivity extends AppCompatActivity {

SortedViewModel viewModel;
AppPreferenceManager preferenceManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
preferenceManager = new AppPreferenceManager(this);
if (preferenceManager.getDarkModeState()){
setTheme(R.style.Dark);
}
else{
setTheme(R.style.AppTheme);
}
setContentView(R.layout.activity_show_sorted);

final SortedAdapter adapter = new SortedAdapter();
RecyclerView showSorted = findViewById(R.id.show_sorted);
showSorted.setLayoutManager(new LinearLayoutManager(this));
showSorted.setHasFixedSize(true);
showSorted.setAdapter(adapter);

getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_close);
setTitle("Sorted");

Intent intent = getIntent();
String currentDate = intent.getStringExtra("value");

viewModel = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication())).get(SortedViewModel.class);
try {
viewModel.getSortedWhereDateIs(currentDate).observe(this, new Observer<List<Sorted>>() {
@Override
public void onChanged(List<Sorted> sorteds) {
adapter.setSortedData(sorteds);
}
});
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

也许数据没有被删除,但是显示有问题?我找不到我的错误...感谢您的帮助。

最佳答案

我猜问题是因为我创建了两个同名的数据库“unsorted_database”。现在看来可以了。

关于java - 为什么Room数据库在重启应用后会丢失数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61589116/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com