EmailRoomDatabase.java 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package com.noahvogt.miniprojekt.ui.DataBase;
  2. import android.content.Context;
  3. import androidx.annotation.NonNull;
  4. import androidx.room.Database;
  5. import androidx.room.Room;
  6. import androidx.room.RoomDatabase;
  7. import androidx.room.migration.Migration;
  8. import androidx.sqlite.db.SupportSQLiteDatabase;
  9. import java.util.concurrent.ExecutorService;
  10. import java.util.concurrent.Executors;
  11. @Database(entities = {Message.class}, version = 1, exportSchema = true)
  12. public abstract class EmailRoomDatabase extends RoomDatabase{
  13. public abstract MessageDao messageDao();
  14. /* the INSTANCE can be used ba different threads at the same time */
  15. private static volatile EmailRoomDatabase INSTANCE;
  16. /* tells room the schema is changed from the version tha is istallend in device
  17. * is not used */
  18. static final Migration MIGRATION_2_3 = new Migration(2, 3) {
  19. @Override
  20. public void migrate(SupportSQLiteDatabase database) {
  21. database.execSQL("ALTER TABLE word_table "
  22. + "ADD COLUMN last_update INTEGER ");
  23. }
  24. };
  25. /* creating 4 threads */
  26. private static final int NUMBER_OF_THREADS = 4;
  27. static final ExecutorService databaseWriteExecutor =
  28. Executors.newFixedThreadPool(NUMBER_OF_THREADS);
  29. static EmailRoomDatabase getDatabase(final Context context) {
  30. if (INSTANCE == null) {
  31. /* synchronize all threads of WordRoomDatabase */
  32. synchronized (EmailRoomDatabase.class) {
  33. if (INSTANCE == null) {
  34. /* passes the interface in the Room and deletes old data/schema from device*/
  35. INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
  36. EmailRoomDatabase.class, "message_database")
  37. .addCallback(sRoomDatabaseCallback)
  38. .fallbackToDestructiveMigration()
  39. .build();
  40. }
  41. }
  42. }
  43. return INSTANCE;
  44. }
  45. private static RoomDatabase.Callback sRoomDatabaseCallback = new RoomDatabase.Callback() {
  46. @Override
  47. public void onCreate(@NonNull SupportSQLiteDatabase db) {
  48. super.onCreate(db);
  49. // If you want to keep data through app restarts,
  50. // comment out the following block
  51. databaseWriteExecutor.execute(() -> {
  52. // Populate the database in the background.
  53. // If you want to start with more words, just add them.
  54. MessageDao dao = INSTANCE.messageDao();
  55. dao.deleteAll();
  56. Message word = new Message("Simon", null, null,
  57. "Noah", "28.8.21", "testing", "I want to try it",
  58. true);
  59. dao.insert(word);
  60. });
  61. }
  62. };
  63. }