Introduction
Hello!
I’d be happy to help you insert data into a Room database using Java in Android. Room is a popular database library for Android that provides an easy-to-use SQLite database solution with built-in support for live data, MVVM architecture, and TypeSafe queries. In this guide, we will explore how to create a Room database, define entities, and insert data.
**Creating a Room Database**
First, let’s create a Room database. Create a new Kotlin or Java class that extends `RoomDatabase` and annotate it with `@Database`.
For instance:
@Database(entities {UserEntity.class}, version 1)
public abstract class AppDatabase extends RoomDatabase {
// ...
}
Defining Entities
Next, define the entity classes that represent your data. Create a new Kotlin or Java class and annotate it with @Entity
.
For example:
@Entity(tableName "users")
public static class UserEntity {
@PrimaryKey(autoGenerate true)
private int id;
private String name;
private int age;
public UserEntity(String name, int age) {
this.name name;
this.age age;
}
}
Accessing the Database
Now, we need to access the database in order to insert data. Create an abstract method that returns a DAO (Data Access Object) of your entity class:
@Database(entities {UserEntity.class}, version 1)
public abstract class AppDatabase extends RoomDatabase {
// ...
public abstract UserDao userDao();
}
Defining DAOs
Next, create a UserDao
interface that extends RoomDao<UserEntity>
.
For example:
<h2>@Dao</h2>
public interface UserDao {
<h3> @Insert</h3>
void insert(UserEntity user);
}
Inserting Data
Finally, we can now insert data into the database. Obtain an instance of your AppDatabase
, then your UserDao
, and call the insert()
method:
@MainThread
public static void insertUser(String name, int age) {
AppDatabase db Room.databaseBuilder(ContextCompat.getApplicationContext(context), AppDatabase.class, "app-db").build();
UserDao userDao db.userDao();
UserEntity newUser new UserEntity(name, age);
userDao.insert(newUser);
}
Summary
In this guide, we learned how to insert data into a Room database using Java in Android. We started by creating a Room database and defining entities. Next, we accessed the database by creating a DAO, then inserted data using the insert()
method.