Room database
Building an Android Application, using Room Database to add new and display
courses:
-Main UI:
-Display data:
1
Solution:
[Link] project
-Click File -> New -> New project -> Empty Activity -> Click Next
-Choose Project name, location, language (java), min SDK -> Click Finish
-Add new activity: ViewActivity
[Link] database
-Add Library:
+Open gradle and add library for Room database:
dependencies {
implementation '[Link]:room-runtime:2.2.5'
annotationProcessor '[Link]:room-compiler:2.2.5'
}
+Click Sync Now
-Create Entities:
+Add class [Link]:
import [Link];
import [Link];
@Entity(tableName = "course_table")//Setting table name
public class Course {
// below line is to auto increment id for each course.
// variable for our id.
@PrimaryKey(autoGenerate = true)
private int id;
// below line is a variable for course name.
private String courseName;
// below line is use for course description.
private String courseDescription;
// below line is use for course duration.
private String courseDuration;
// below line we are creating constructor class.
// inside constructor class we are not passing
// our id because it is incrementing automatically.
2
public Course(String courseName, String courseDescription,
String courseDuration) {
[Link] = courseName;
[Link] = courseDescription;
[Link] = courseDuration;
}
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
[Link] = courseName;
}
public String getCourseDescription() {
return courseDescription;
}
public void setCourseDescription(String courseDescription)
{
[Link] = courseDescription;
}
public String getCourseDuration() {
return courseDuration;
}
public void setCourseDuration(String courseDuration) {
[Link] = courseDuration;
}
public int getId() {
return id;
}
public void setId(int id) {
[Link] = id;
}
}
-Create DAO:
+Add interface Dao
3
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
// adding annotation to our Dao class
@[Link]
public interface Dao {
// below method is use to add data to database.
@Insert
void insert(Course model);
// below method is use to update the data in our database.
@Update
void update(Course model);
// below line is use to delete a specific course in our
database.
@Delete
void delete(Course model);
// on below line we are making query to delete all courses
from our database.
@Query("DELETE FROM course_table")
void deleteAllCourses();
// below line is to read all the courses from our database.
// in this we are ordering our courses in ascending order
with our course name.
@Query("SELECT * FROM course_table ORDER BY courseName ASC")
List<Course> getAllCourses();
}
-Create database:
+Add class: [Link]
4
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
// adding annotation for our database entities and db version.
@Database(entities = {[Link]}, version = 1)
public abstract class CourseDatabase extends RoomDatabase {
// below line is to create instance for our database class.
private static CourseDatabase instance;
// below line is to create
// abstract variable for dao.
public abstract Dao Dao();
// on below line we are getting instance for our database.
public static synchronized CourseDatabase getInstance(Context
context) {
// below line is to check if the instance is null or not.
if (instance == null) {
// if the instance is null we are creating a new
instance
instance =
// for creating a instance for our database
// we are creating a database builder and
passing
// our database class with our database name.
[Link]([Link](),
[Link],
"course_database")
// below line is use to add fall back
to
// destructive migration to our
database.
.fallbackToDestructiveMigration()
// below line is to add callback
// to our database.
.addCallback(roomCallback)
.allowMainThreadQueries()
// below line is to
// build our database.
.build();
5
}
// after creating an instance
// we are returning our instance
return instance;
}
// below line is to create a callback for our room database.
private static [Link] roomCallback = new
[Link]() {
@Override
public void onCreate(@NonNull SupportSQLiteDatabase db) {
[Link](db);
// this method is called when database is created
// and below line is to populate our data.
new PopulateDbAsyncTask(instance).execute();
}
};
// we are creating an async task class to perform task in
background.
private static class PopulateDbAsyncTask extends
AsyncTask<Void, Void, Void> {
PopulateDbAsyncTask(CourseDatabase instance) {
Dao dao = [Link]();
}
@Override
protected Void doInBackground(Void... voids) {
return null;
}
}
}
-Create Repository:
+Add class: [Link]
import [Link];
import [Link];
public class CourseRepository {
// below line is the create a variable
// for dao and list for all courses.
public static Dao dao;
// creating a constructor for our variables
// and passing the variables to it.
6
public CourseRepository(Application application) {
CourseDatabase database =
[Link](application);
dao = [Link]();
}
// creating a method to insert the data to our database.
public void insert(Course course) {
[Link](course);
}
// creating a method to update data in database.
public void update(Course course) {
[Link](course);
}
// creating a method to delete the data in our database.
public void delete(Course course) {
[Link](course);
}
// below is the method to delete all the courses.
public void deleteAll() {
[Link]();
}
// below method is to read all the courses.
public List<Course> getAll() {
return [Link]();
}
}
3. Main Activity
-Add colors to [Link]
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="purple_200">#FFBB86FC</color>
<color name="purple_500">#FF6200EE</color>
<color name="purple_700">#FF3700B3</color>
<color name="teal_200">#FF03DAC5</color>
<color name="teal_700">#FF018786</color>
<color name="black">#FF000000</color>
<color name="white">#FFFFFFFF</color>
<color name="buttonColor">#0F9D58</color>
7
<color name="textColor">#FFFFFF</color>
</resources>
-activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<!--Edit text to enter course name-->
<EditText
android:id="@+id/edtName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:hint="Enter course Name" />
<!--Edit text for course description-->
<EditText
android:id="@+id/edtDescription"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:hint="Enter Course Description" />
<!--Edit text to enter course duration-->
<EditText
android:id="@+id/edtDuration"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:hint="Enter Course Duration" />
<!--button for adding new course-->
<Button
android:id="@+id/btnAddCourse"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Add New Course"
android:textAllCaps="false"
8
android:backgroundTint="@color/buttonColor"/>
<Button
android:id="@+id/btnReadCourses"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Read All Courses"
android:textAllCaps="false"
android:backgroundTint="@color/buttonColor"/>
</LinearLayout>
-[Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends AppCompatActivity {
private EditText edtCourseName, edtCourseDescription,
edtCourseDuration;
private Button btnAddCourse, btnReadCourses;
CourseRepository res;
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
// initializing all our variables
edtCourseName = findViewById([Link]);
edtCourseDescription =
findViewById([Link]);
edtCourseDuration = findViewById([Link]);
btnAddCourse = findViewById([Link]);
btnReadCourses = findViewById([Link]);
9
res = new CourseRepository(getApplication());
[Link](new
[Link]() {
public void onClick(View v) {
addCourse();
}
});
[Link](new
[Link]()
{
public void onClick (View v){
//Opening ViewCourses activity via a intent
Intent i = new Intent([Link],
[Link]);
startActivity(i);
}
});
}
public void addCourse()
{
//Getting data from all edit text fields
Course course = new
Course([Link]().toString(),edtCourseDescription.g
etText().toString(),[Link]().toString());
//Adding a new course to sqlite data and pass all our
values to it.
[Link](course);
//After adding the data we are displaying a toast
message
[Link]([Link], "Course has been
added.", Toast.LENGTH_SHORT).show();
[Link]("");
[Link]("");
[Link]("");
}
}
[Link] course
-activity_view.xml
10
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ViewActivity">
<!--recycler view for displaying our courses-->
<[Link]
android:id="@+id/rvCourses"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
-Layout for an item:
+Add Layout Resource File: course_item.xml
<?xml version="1.0" encoding="utf-8"?>
<[Link]
xmlns:android="[Link]
xmlns:app="[Link]
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:elevation="8dp"
app:cardCornerRadius="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="3dp"
android:orientation="vertical">
<!--text view for our course name-->
<TextView
android:id="@+id/tvCourseName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="3dp"
android:text="Name"
android:textColor="@color/black" />
11
<TextView
android:id="@+id/tvCourseDescription"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="3dp"
android:text="Description"
android:textColor="@color/black" />
<TextView
android:id="@+id/tvCourseDuration"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="3dp"
android:text="Duration"
android:textColor="@color/black" />
</LinearLayout>
</[Link]>
-Adapter and ViewHolder
+Add class: [Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class CourseRVAdapter extends
[Link]<[Link]> {
// variable for our array list and context
private ArrayList<Course> courseModalArrayList;
private Context context;
// constructor
public CourseRVAdapter(ArrayList<Course>
courseModalArrayList, Context context) {
12
[Link] = courseModalArrayList;
[Link] = context;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup
parent, int viewType) {
// on below line we are inflating our layout
// file for our recycler view items.
View view =
[Link]([Link]()).inflate([Link]
_item, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int
position) {
// on below line we are setting data
// to our views of recycler view item.
Course modal = [Link](position);
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
// below line is to add on click listener for our recycler
view item.
[Link](new
[Link]() {
@Override
public void onClick(View v) {
//Update, delete
}
});
}
@Override
public int getItemCount() {
// returning the size of our array list
return [Link]();
}
public class ViewHolder extends [Link] {
// creating variables for our text views.
13
private TextView tvCourseName, tvCourseDesc,
tvCourseDuration;
public ViewHolder(@NonNull View itemView) {
super(itemView);
// initializing our text views
tvCourseName =
[Link]([Link]);
tvCourseDesc =
[Link]([Link]);
tvCourseDuration =
[Link]([Link]);
}
}
}
-[Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class ViewActivity extends AppCompatActivity {
private ArrayList<Course> courses;
private CourseRVAdapter adapter;
private RecyclerView rvCourses;
CourseRepository res;
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_view);
// getting data
res = new CourseRepository(getApplication());
courses = new ArrayList<Course>();
List<Course> data = [Link]();
for (int i = 0; i < [Link](); i++) {
String name = [Link](i).getCourseName();
String des = [Link](i).getCourseDescription();
14
String dur = [Link](i).getCourseDuration();
[Link](new Course(name, des, dur));
}
//Passing array list to our adapter class
adapter = new CourseRVAdapter(courses,
[Link]);
//Creating recycler view
rvCourses = findViewById([Link]);
LinearLayoutManager linearLayoutManager = new
LinearLayoutManager([Link], [Link],
false);
[Link](linearLayoutManager);
[Link](adapter);//Setting our adapter to
recycler view
}
}
15