Ruthwik Warrier
Ruthwik Warrier

Reputation: 197

Android Room Pagination - How can read from two tables?

I have a table Posts which stores forum posts from the server. The posts have comments that I am storing under different table called Comments. Currently, I am using Room pagination library with PagedAdapter to list the posts from the database. Now I have a requirement to show top comments along with posts. How can I combine the results from two tables into a single DataSource? What is the proper way to handle this situation?

Upvotes: 0

Views: 453

Answers (1)

Itamar Kerbel
Itamar Kerbel

Reputation: 2568

The short answer is that you need to use relations. Example:

@Entity
public class Comment{
    @PrimaryKey
    public int id;     // comment id
    public int postId; // post id this comment belongs to
    public String comment;
}

This is a POJO for a post with comments which will be the result of the query

// Note: No annotation required at this class definition.
public class PostWithComments {
   @Embedded
   public Post post;

   @Relation(parentColumn = "id", entityColumn = "postId", entity = Comment.class)
   public List<Comment> comments;
}

Your query will be:

@Dao
 public interface PostCommentsDao {
     //Query
    @Query("SELECT * FROM Post")
    public List<PostWithComments> loadPostWithComments();
 }

This will get all the posts with all the comments that belong to each post wraped up in the nice POJO.

Upvotes: 1

Related Questions