본문 바로가기
Study Log/Software Engineering

데이그램 따라하기 - 4. Realm DB

by HZie 2020. 8. 19.

메모 리스트 저장 및 출력 구현 - Realm DB

Realm DB
  - 모바일 사용에 최적화된 내장 데이터베이스 라이브러리
  - NoSQL DB를 지향
  - 모델 구조 자체가 객체로 구성되어 있고 자체의 API를 통해 실행된다
      - 클래스 객체의 멤버 변수 값을 저장한다고 생각하면 된다고 한다.
      - 장점: 직관적인 사용, 빠른 데이터 처리 속도
      - 단점: 자체 사용법을 익혀야 함
  - 서버에서 사용시 실시간 동기화가 가능함
  - 테이블 구조가 아님
 
  [안드로이드 스튜디오에서 사용 방법]
  1. 프로젝트 수준의 build.gradle에 dependency 추가

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath "io.realm:realm-gradle-plugin:3.5.0"
    }
}

 

  2. 어플리케이션 수준의 build.gradle에 플러그인 적용 (!! Maven과 Ant 빌드시스템에서는 지원되지 않음 !!)

apply plugin: 'realm-android'

  gradle을 수정한 후에는 꼭 sync를 해주자  

관련 문서: https://realm.io/kr/docs/
참고 자료: https://hellominchan.tistory.com/27

  [데이그램 따라하기 프로젝트에서 적용하기]
 
  1. gradle 파일 수정하기
      (1) build.gradle(Project:  ...)

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:4.0.0"
        classpath "io.realm:realm-gradle-plugin:3.5.0"
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}


      (2) build.gradle(Module: app)

apply plugin: 'com.android.application'
apply plugin: 'realm-android'

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.0"

    defaultConfig {
        applicationId "com.example.daygram_clone"
        minSdkVersion 26
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    buildFeatures {
        viewBinding true
    }
}
dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.recyclerview:recyclerview:1.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}

 

  2. 메모를 저장할 Memo 객체 만들기
      - realm DB에 저장하기 위해 realm 객체로 만들어야 한다. 따라서 클래스는 RealmObject를 상속받아야 한다.

package com.example.daygram_clone;

import io.realm.RealmObject;

public class Memo extends RealmObject {

    // 멤버 변수
    private int year;
    private int month;
    private int date;
    private String memo;

    // 모두 private이므로 getter와 setter를 생성한다.

    public int getYear(){
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public int getMonth() {
        return month;
    }

    public void setMonth(int month) {
        this.month = month;
    }

    public int getDate(){
        return date;
    }

    public void setDate(int date) {
        this.date = date;
    }

    public String getMemo(){
        return memo;
    }

    public void setMemo(String memo) {
        this.memo = memo;
    }
}

 

  3. Main Activity에서 메모를 realm DB에 저장하기
      (1) onCreate에서 realm을 init해준다

Realm.init(this);

      (2) 메모 객체를 생성하고 getter와 setter를 이용해 멤버 변수를 설정한다.
      (3) Realm을 이용해 생성된 메모 객체를 DB에 저장한다.

Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
realm.copyToRealm(memo);
realm.commitTransaction();
realm.close();
finish();

 

  4. 저장한 데이터 가져오기
      - MainAdpater 생성자에서 메모 객체를 저장하기위한 변수를 생성하고 DB query를 이용해 리스트를 불러온다.

        // 메모 객체를 저장하기 위한 변수
        RealmResults<Memo> results;

        // Realm DB에 저장된 메모들의 query를 이용해 해당 연,월의 memo 리스트를 불러온다.
        Realm realm = Realm.getDefaultInstance();
        RealmQuery<Memo> query = realm.where(Memo.class);
        results = query
                .equalTo("year",year)
                .equalTo("month",month)
                .findAll();
        
        for(Memo m: results){
            memos[m.getDate()-1] = m.getMemo();
        }


따라하기 출처: https://codeasy.tistory.com/31?category=751342

댓글