In the previous article, we have seen adding data to the realm database in Android. In this article, we will take a look at reading this data from our Realm Database in the Android app.
What we are going to build in this article?
In this article, we will be simply adding a Button to open a new activity in the project which we have created in the previous article. Inside the new activity, we will display data in the form of RecyclerView. Below is the video in which we will get to see what we are going to build in this article.
Step by Step Implementation
Step 1: Working with the activity_main.xml file
Go to the activity_main.xml file and add a new Button to open a new activity for displaying our list of courses.
Now below is the updated code for the activity_main.xml file after adding the above code snippet.
Step 2: Working with the MainActivity.java file
As we have added a new button to our activity_main.xml file, so we have to add setOnClickListener() to that button in our MainActivity.java file.
Below is the updated code for the MainActivity.java file after adding the above code snippet.
Step 3: Creating a new Activity for displaying our list of courses
To create a new Activity we have to navigate to the app > java > your app’s package name > Right click on package name > New > Empty Activity and name your activity as ReadCoursesActivity and create new Activity. Make sure to select the empty activity.
Step 4: Creating a new layout file for our item of RecyclerView
Navigate to the app > res > layout > Right-click on it > New > Layout resource file and name it as course_rv_item and add the below code to it.
Step 5: Creating an Adapter class for setting data to our items of RecyclerView
Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as CourseRVAdapter and add the below code to it. Comments are added inside the code to understand the code in more detail.
Step 6: Working with the activity_read_courses.xml file
Navigate to the app > res > layout > activity_read_courses.xml and add the below code to that file. Below is the code for the activity_read_courses.xml file.
Step 7: Working with the ReadCoursesActivity.java file
Navigate to the app > java > your app’s package name > ReadCoursesActivity.java file and add the below code to it. Comments are added inside the code to understand the code in more detail.
Now run your app and see the output of the app.
Below is the complete project file structure after performing the read operation:
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.