[Android] Room DataBase 1편

ParkGil-hyeon·2021년 11월 29일
0

android

목록 보기
1/2
post-thumbnail

배경

모바일 프로그래밍 팀 프로젝트가 시작되었다.

그동안 안드로이드 개발은 서버팀에서 개발한 API를 사용해서 진행해왔었다.
하지만 이번 팀 프로젝트 때는 서버팀이 따로 존재하지 않았고 개발을 처음 접하시는 분들도 계셨다.

그래서 최소한의 노력으로 최대한의 성과를 낼 수 있는 방향에 집중했다.

공동구매 소비자들은 공동구매 앱에서 물건을 구매하는 것을 원하지 않는다.
그 사람들은 본인이 사고 싶은 물건을 판매하는 링크를 어떻게 구할 수 있는지에 관심이 있었다.

이러한 문제를 해결하기 위해 우리는 카카오톡, 인스타, 네이버 카페 등
많은 곳에 흩어져 있는 공동구매 링크를 모아주는 앱을 기획했다.

Room DB를 선택한 계기

"최소한의 구성으로 구현할 수 있는 핵심 기능"에 초점을 맞췄지만 상품들을 GridView로
그려야했기 때문에 데이터베이스는 필수적이었다.

누구나 1시간만에 개발할 수 있는 간단한 내부 DB를 활용하기로 했다.
그리고 Room이란 것을 알게되었다.

Android Docs

https://developer.android.com/docs 라는 곳에서 친절하게도 안드로이드의 거의 모든 문서를 제공한다.

1. Gradle 종속 항목 추가


일단 Gradle에 Room을 사용하기 위한 코드들을 작성하고 Build를 해야한다.

def room_version = "2.3.0"
implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"

2. Room의 주요 구성요소 생성


우리는 게시글을 저장하는 DB를 만들 계획이다.
문서에 맞게 Appdatabase, Post, PostDao를 만들었다.

//Post의 코드(Setter, Getter 생략)
@Entity
public class Post {
    @PrimaryKey(autoGenerate = true)
    private int id;
    private int post_id;
    private String user_id;
    private String keyword;
    private String title;
    private String content;
    private Integer target;
    private Integer people;
    private String url;
    private String date;
    private String uri_image;
    private Integer id_drawable;
    private String channel;
    public Post(int post_id, String user_id, String keyword, String title, String content,
                Integer target, Integer people, String url, String date, String uri_image,
                Integer id_drawable, String channel) {
        this.id = id;
        this.post_id = post_id;
        this.user_id = user_id;
        this.keyword = keyword;
        this.title = title;
        this.content = content;
        this.target = target;
        this.people = people;
        this.url = url;
        this.date = date;
        this.uri_image = uri_image;
        this.id_drawable = id_drawable;
        this.channel = channel;
    }
}
// PostDao의 코드
@Dao
public interface PostDao {
    @Query("SELECT * FROM Post")
    List<Post> getAll();
    @Insert
    void insert(Post post);
    @Update
    void updatePost(Post post);
    @Delete
    void deletePost(Post post);
    @Query("DELETE FROM Post")
    void clearAll();
}
//Appdatabase의 코드
@Database(entities = {Post.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
    public abstract PostDao postDao();
}

이렇게 하면 Room DB를 사용하기 위한 모든 준비가 끝이 났다.
2편에서 Room DB에 저장하는 방법과 데이터를 가져오는 방법을 알아보자.

profile
개발자

0개의 댓글