210202

[Java] Room 기초적인 사용법 본문

Android/기능구현

[Java] Room 기초적인 사용법

dev210202 2020. 7. 30. 16:40

아래 사이트를 참고해서 구현했다.

https://www.youtube.com/watch?v=pG6OkJ3rSjg&list=PLxTmPHxRH3VXHOBnaGQcbSGslbAjr8obc

1. build.gradle 세팅

implementation 'androidx.room:room-runtime:2.2.5'
annotationProcessor 'androidx.room:room-compiler:2.2.5'

2. DTO 생성

@Entity
public class Todo {
    @PrimaryKey(autoGenerate = true)
    private int id;
    private String title;
    public Todo(String title) {
        this.title = title;
    }


    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    @Override
    public String toString() {
        return "Todo{" +
                "id=" + id +
                ", title='" + title + '\'' +
                '}';
    }
}

 

 

3. DAO 생성

@Dao
public interface TodoDao {
    @Query("SELECT * FROM Todo")
    List<Todo> getAll();

    @Insert
    void insert(Todo todo);

    @Update
    void update(Todo todo);

    @Delete
    void delete(Todo todo);
}

4. DB 클래스 생성

@Database(entities = {Todo.class}, version = 1)
abstract class AppDatabase extends RoomDatabase {
   public abstract TodoDao todoDao();
}

5. 메인에 세팅

public class MainActivity extends AppCompatActivity {
    TextView resultTextView;
    EditText todoEditText;
    Button addButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        resultTextView = findViewById(R.id.result_textview);
        todoEditText = findViewById(R.id.todo_edittext);
        addButton = findViewById(R.id.add_button);

        final AppDatabase db = Room.databaseBuilder(this, AppDatabase.class, "todo-db")
                .allowMainThreadQueries()
                .build();
        resultTextView.setText(db.todoDao().getAll().toString());
        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                db.todoDao().insert(new Todo(todoEditText.getText().toString()));
                resultTextView.setText(db.todoDao().getAll().toString());
            }
        });
    }
}

 

 
Comments