简体   繁体   中英

Why does Room database lose data after restarting the app?

I'm using Room Persistance library with all Android Architucture Components. In the app I have 3 databases, but the problem is with only one. In my MainActivity I have a RecyclerView that show data (dates) from DatesDatabase. When clicking on each element, a new activity opens and shows all the data that refers to particular date. The query in DAO is:

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

Problem is that when I restart the app I still can see the dates, that have been added earlier, but there is no data that refers to this date.

Before restarting: screenshot1 screenshot2

After restarting: screenshot1 screenshot2

Code to DatesDatabase:

@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;
}
}

Code to database, that doesn't save data:

@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;
}
}

I tried to delete "fallbackToDestructiveMigration()", but I have a method "deleteAll", that shows error in this case:

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

Here is how I add data to SortedDatabase(that gets deleted):

 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);
        }

I sort tasks of class Unsorted, stored in UnsortedDatabase, through algorithm and then add it to SortedDatabase.

My adapter to recyclerview that shows sorted data:

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);
    }
}
}

And, finally, activity, where data is shown:

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();
    }
}
}

Maybe the data isn't deleted, but there is a problem with displaying it? I could't find my mistake... Thanks for any help.

I guess the problem was because of me creating two databases with the same name "unsorted_database". It seems to work now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM