How to initialize room persistent library database with retrofit retrieved model information?

Viewed 2033

im having trouble understanding how to use retrofit with android persistent library room.

Lets say i have the following model entity defined:

Entity(tableName = MY_EVENT_TABLE)
public class Event {
   public static final String TABLE_NAME = "events";
   public static final String DATE_FIELD = "date";

   @PrimaryKey(autoGenerate = true)
   private int id;
   private String name;
   private String description;
   @ColumnInfo(name = DATE_FIELD)
   private LocalDateTime date;

   public Event(int id, String name, String description, LocalDateTime date) {
       this.id = id;
       this.name = name;
       this.description = description;
       this.date = date;
   }

   public int getId() {
       return id;
   }

   public String getName() {
       return name;
   }

   public String getDescription() {
       return description;
   }

   public LocalDateTime getDate() {
       return date;
   }

   @Override
   public String toString() {
       return "Event{" +
               "id=" + id +
               ", name='" + name + '\'' +
               ", description='" + description + '\'' +
               ", date=" + date +
               '}';
   }

   public long getDaysUntil() {
       return ChronoUnit.DAYS.between(LocalDateTime.now(), getDate());
   }
}

and lets say im getting this information initially from a webservice with retrofit. so after i call the retrofit service it will return a class (using gson) populated of type Event.

So all's good now we have a fully populated class called Event with data from our rest server through a retrofit api service call.

now i'd like to make sure this information goes into room persistent library. How do i do this:

even if i build the database im just passing it the class name not the actual class retrofit returned.

For example to build a room database i'd do:

Room.databaseBuilder(context.getApplicationContext(), EventDatabase.class, "event_db").build();

and now we have a event database but how do i get my information from retrofit into the DB table MY_EVENT_TABLE ?

I HAVE AN idea but not sure its correct or efficient. if i have a dao like this in room:

@Dao
public interface EventDao {

   @Query("SELECT * FROM " + Event.TABLE_NAME + " WHERE " + Event.DATE_FIELD + " > :minDate")
   LiveData<List<Event>> getEvents(LocalDateTime minDate);

   @Insert(onConflict = REPLACE)
   void addEvent(Event event);

   @Delete
   void deleteEvent(Event event);

   @Update(onConflict = REPLACE)
   void updateEvent(Event event);

}

could i just call the DAO insert method after i get the data from the server ?

so it would be : eventDao.addEvent(event);

is that the recommended way ?

0 Answers
Related