0% found this document useful (0 votes)
49 views15 pages

Exercise 9 - Room Database - Java

The document describes how to build an Android application using Room database to add and display course data. It involves creating entities to define the data model, a DAO interface to access the database, a database class to abstract the connection, and a repository to separate the data layer from the rest of the app. MainActivity is then built with UI elements like edit texts and buttons to add, view, and manage the course data.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
49 views15 pages

Exercise 9 - Room Database - Java

The document describes how to build an Android application using Room database to add and display course data. It involves creating entities to define the data model, a DAO interface to access the database, a database class to abstract the connection, and a repository to separate the data layer from the rest of the app. MainActivity is then built with UI elements like edit texts and buttons to add, view, and manage the course data.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 15

Room database

Building an Android Application, using Room Database to add new and display
courses:
-Main UI:

-Display data:

1
Solution:
1.Create project
-Click File -> New -> New project -> Empty Activity -> Click Next
-Choose Project name, location, language (java), min SDK -> Click Finish
-Add new activity: ViewActivity

2.Room database
-Add Library:
+Open gradle and add library for Room database:
dependencies {
implementation 'androidx.room:room-runtime:2.2.5'
annotationProcessor 'androidx.room:room-compiler:2.2.5'
}
+Click Sync Now

-Create Entities:
+Add class Course.java:
import androidx.room.Entity;
import androidx.room.PrimaryKey;

@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) {
this.courseName = courseName;
this.courseDescription = courseDescription;
this.courseDuration = courseDuration;
}

public String getCourseName() {


return courseName;
}

public void setCourseName(String courseName) {


this.courseName = courseName;
}

public String getCourseDescription() {


return courseDescription;
}

public void setCourseDescription(String courseDescription)


{
this.courseDescription = courseDescription;
}

public String getCourseDuration() {


return courseDuration;
}

public void setCourseDuration(String courseDuration) {


this.courseDuration = courseDuration;
}

public int getId() {


return id;
}

public void setId(int id) {


this.id = id;
}
}

-Create DAO:
+Add interface Dao

3
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.Update;
import java.util.List;

// adding annotation to our Dao class


@androidx.room.Dao
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: CourseDatabase.java

4
import android.content.Context;
import android.os.AsyncTask;

import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.sqlite.db.SupportSQLiteDatabase;

// adding annotation for our database entities and db version.


@Database(entities = {Course.class}, 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.

Room.databaseBuilder(context.getApplicationContext(),
CourseDatabase.class,
"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 RoomDatabase.Callback roomCallback = new
RoomDatabase.Callback() {
@Override
public void onCreate(@NonNull SupportSQLiteDatabase db) {
super.onCreate(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 = instance.Dao();
}
@Override
protected Void doInBackground(Void... voids) {
return null;
}
}
}

-Create Repository:
+Add class: CourseRepository.java
import android.app.Application;
import java.util.List;

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 =
CourseDatabase.getInstance(application);
dao = database.Dao();
}

// creating a method to insert the data to our database.


public void insert(Course course) {
dao.insert(course);
}

// creating a method to update data in database.


public void update(Course course) {
dao.update(course);
}

// creating a method to delete the data in our database.


public void delete(Course course) {
dao.delete(course);
}

// below is the method to delete all the courses.


public void deleteAll() {
dao.deleteAllCourses();
}

// below method is to read all the courses.


public List<Course> getAll() {
return dao.getAllCourses();
}
}

3. Main Activity
-Add colors to colors.xml
<?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="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
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>

-MainActity.java
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


private EditText edtCourseName, edtCourseDescription,
edtCourseDuration;
private Button btnAddCourse, btnReadCourses;

CourseRepository res;

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

// initializing all our variables


edtCourseName = findViewById(R.id.edtName);
edtCourseDescription =
findViewById(R.id.edtDescription);
edtCourseDuration = findViewById(R.id.edtDuration);

btnAddCourse = findViewById(R.id.btnAddCourse);
btnReadCourses = findViewById(R.id.btnReadCourses);

9
res = new CourseRepository(getApplication());

btnAddCourse.setOnClickListener(new
View.OnClickListener() {
public void onClick(View v) {
addCourse();
}
});

btnReadCourses.setOnClickListener(new
View.OnClickListener()
{
public void onClick (View v){
//Opening ViewCourses activity via a intent
Intent i = new Intent(MainActivity.this,
ViewActivity.class);
startActivity(i);
}
});
}

public void addCourse()


{
//Getting data from all edit text fields
Course course = new
Course(edtCourseName.getText().toString(),edtCourseDescription.g
etText().toString(),edtCourseDuration.getText().toString());

//Adding a new course to sqlite data and pass all our


values to it.
res.insert(course);

//After adding the data we are displaying a toast


message
Toast.makeText(MainActivity.this, "Course has been
added.", Toast.LENGTH_SHORT).show();
edtCourseName.setText("");
edtCourseDescription.setText("");
edtCourseDuration.setText("");
}
}

4.View course
-activity_view.xml

10
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ViewActivity">

<!--recycler view for displaying our courses-->


<androidx.recyclerview.widget.RecyclerView
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"?>

<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
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>

</androidx.cardview.widget.CardView>

-Adapter and ViewHolder


+Add class: CourseRVAdapter.java
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;

public class CourseRVAdapter extends


RecyclerView.Adapter<CourseRVAdapter.ViewHolder> {

// variable for our array list and context


private ArrayList<Course> courseModalArrayList;
private Context context;

// constructor
public CourseRVAdapter(ArrayList<Course>
courseModalArrayList, Context context) {

12
this.courseModalArrayList = courseModalArrayList;
this.context = 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 =
LayoutInflater.from(parent.getContext()).inflate(R.layout.course
_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 = courseModalArrayList.get(position);
holder.tvCourseName.setText(modal.getCourseName());
holder.tvCourseDesc.setText(modal.getCourseDescription());

holder.tvCourseDuration.setText(modal.getCourseDuration());

// below line is to add on click listener for our recycler


view item.
holder.itemView.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
//Update, delete
}
});
}

@Override
public int getItemCount() {
// returning the size of our array list
return courseModalArrayList.size();
}

public class ViewHolder extends RecyclerView.ViewHolder {

// creating variables for our text views.

13
private TextView tvCourseName, tvCourseDesc,
tvCourseDuration;

public ViewHolder(@NonNull View itemView) {


super(itemView);
// initializing our text views
tvCourseName =
itemView.findViewById(R.id.tvCourseName);
tvCourseDesc =
itemView.findViewById(R.id.tvCourseDescription);
tvCourseDuration =
itemView.findViewById(R.id.tvCourseDuration);
}
}
}

-ViewActivity.java
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;

import java.util.ArrayList;
import java.util.List;

public class ViewActivity extends AppCompatActivity {


private ArrayList<Course> courses;

private CourseRVAdapter adapter;


private RecyclerView rvCourses;

CourseRepository res;

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

// getting data
res = new CourseRepository(getApplication());
courses = new ArrayList<Course>();
List<Course> data = res.getAll();
for (int i = 0; i < data.size(); i++) {
String name = data.get(i).getCourseName();
String des = data.get(i).getCourseDescription();

14
String dur = data.get(i).getCourseDuration();
courses.add(new Course(name, des, dur));
}

//Passing array list to our adapter class


adapter = new CourseRVAdapter(courses,
ViewActivity.this);

//Creating recycler view


rvCourses = findViewById(R.id.rvCourses);
LinearLayoutManager linearLayoutManager = new
LinearLayoutManager(ViewActivity.this, RecyclerView.VERTICAL,
false);
rvCourses.setLayoutManager(linearLayoutManager);
rvCourses.setAdapter(adapter);//Setting our adapter to
recycler view
}
}

15

You might also like