Realm is an alternative for SQLite database which is very efficient and much faster in comparison to SQLite. It is a mobile database which is a good substitute for other databases.
Realm reduces the size of the application because it occupies very less memory space as compared to SQLite. It is very fast in reading and writing data. Realm is also cross-platform that supports both iOS and Android.
There are some disadvantages too like ID can’t be generated automatically in the Realm database. If we want to save the object in the Realm database, then the class of the object should extend with RealmObject.
Realm supports the following field types:
- boolean
- byte
- short
- int
- long
- float
- double
- string
- Date
- byte[]
Some Annotations used in Realm Database
@PrimaryKey: This annotation defines that the field is set as a Primary key and must not be null.
@Required: This annotation can be used to tell Realm to enforce checks to disallow null values.
@Ignore: This annotation is for fields that should not be persisted to the disk.
@Index: This annotation will add a search index to the field.
Let’s see how we can implement the Realm database in our application.
Example with Code
Here, we are going to create a simple example where we can Add a person’s details like his/her name, e-mail, address, and age, and we can also Update and Delete these details.
- Create an Application RealmDatabaseExampleAndroid.
Requirements
MainActivity.java, PersonDetailsModel.java, PersonDetailsAdapter.java, PersonDetailsActivity.java, activity_main.xml, activity_person_details.xml, content_main.xml, details_dialog.xml, list_item.xml.
Before creating this classes and xml file, we have to first add the dependency for Realm in our build.gradle file.
build.gradle
Add the dependencies in our build.gradle file.
dependencies { compile 'io.realm:realm-android:0.86.0' compile 'com.android.support:cardview-v7:23.4.0' compile 'com.android.support:design:23.3.0' }
Now, create all the files one by one in our project.
PersonDetailsModel.java
Create this model class and extends with RealmObject as we discussed above.
Code:
public class PersonDetailsModel extends RealmObject { @PrimaryKey private int id; private String name; private String email; private String address; private int age; // generate its setters and getters }
Here, ID is a primary key.
content_main.xml
Code:
<ListView android:id="@+id/listView_PersonName" android:layout_width="match_parent" android:layout_height="wrap_content" />
list_item.xml
Create this xml file to list items in a row. Here, we show the person’s name, edit, and delete button.
Code:
<android.support.v7.widget.CardView android:layout_width="match_parent" android:layout_height="50dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/tv_Name" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_weight="0.9" android:padding="10dp" /> <ImageView android:id="@+id/iv_Edit" android:layout_width="20dp" android:layout_height="20dp" android:layout_gravity="center_vertical" android:layout_marginEnd="10dp" android:layout_marginRight="10dp" android:src="@android:drawable/ic_menu_edit" /> <ImageView android:id="@+id/iv_Delete" android:layout_width="20dp" android:layout_height="20dp" android:layout_gravity="center_vertical" android:layout_marginEnd="10dp" android:layout_marginRight="10dp" android:src="@android:drawable/ic_menu_delete" /> </LinearLayout> </android.support.v7.widget.CardView>
details_dialog.xml
Create this xml file for dialog when a user adds his/her details. Here, we show EditText’s for name, e-mail, address, and age.
Code:
<EditText android:id="@+id/et_Name" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:hint="@string/person_name_hint" /> <EditText android:id="@+id/et_Email" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:hint="@string/person_email_hint" /> <EditText android:id="@+id/et_Address" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:hint="@string/perosn_address_hint" /> <EditText android:id="@+id/et_Age" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:hint="@string/person_age_hint" android:inputType="number" />
activity_main.xml
This is our main activity layout file. Here, we will show the list of person and floating action button for adding new details.
Code
<android.support.design.widget.AppBarLayout android:id="@+id/appbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" app:contentScrim="?attr/colorPrimary" app:layout_scrollFlags="enterAlways" /> </android.support.design.widget.AppBarLayout> <include layout="@layout/content_main" /> <android.support.design.widget.FloatingActionButton android:id="@+id/fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="16dp" android:src="@android:drawable/ic_input_add" app:backgroundTint="@color/colorPrimary" app:elevation="4dp" android:layout_gravity="bottom|right|end" />
PersonDetailsAdapter.java
Create this custom adapter class and extends with BaseAdapter. Here, we will inflate the view of a person like its name, delete and edit the image.
Add the code in the getView() method:
holder.tvPersonName = (TextView) v.findViewById(R.id.tv_Name); holder.ivEditPesonDetail=(ImageView)v.findViewById(R.id.iv_Edit); holder.ivDeletePerson=(ImageView)v.findViewById(R.id.iv_Delete); holder.tvPersonName.setText(personDetailsArrayList.get(position).getName());
To Edit the Details
holder.ivEditPesonDetail.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { PersonDetailsModel dataToEditModel= MainActivity.getInstance().searchPerson(personDetailsArrayList.get(position).getId()); MainActivity.getInstance().addOrUpdatePersonDetailsDialog(dataToEditModel,position); } }); holder.ivDeletePerson.setOnClickListener(new View.OnClickListener() {
To Delete the Record
@Override public void onClick(View v) { ShowConfirmDialog(context,personDetailsArrayList.get(position).getId(), position); } }); public static void ShowConfirmDialog(Context context,final int personId,final int position) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); alertDialogBuilder .setMessage("Are you sure you want to delete this record?") .setCancelable(true) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { MainActivity.getInstance().deletePerson(personId,position); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { dialog.cancel(); } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); }
MainActivity.java
This is our main activity. Here, we will create the instance of Realm class, take the reference of widgets and do all the properties for inserting new data, delete, and update operations.
Initialize:
private FloatingActionButton fab_AddPerson; private Realm myRealm; private ListView lv_PersonName;
Add the code in onCreate(..){..}:
myRealm = Realm.getInstance(MainActivity.this); fab_AddPerson = (FloatingActionButton) findViewById(R.id.fab); lv_PersonName = (ListView) findViewById(R.id.listView_PersonName);
Set the Adapter:
personDetailsAdapter = new PersonDetailsAdapter(MainActivity.this, personDetailsModelArrayList); lv_PersonName.setAdapter(personDetailsAdapter);
Add Data to Realm:
private void addDataToRealm(PersonDetailsModel model) { myRealm.beginTransaction(); PersonDetailsModel personDetailsModel = myRealm.createObject(PersonDetailsModel.class); personDetailsModel.setId(id); personDetailsModel.setName(model.getName()); personDetailsModel.setEmail(model.getEmail()); personDetailsModel.setAddress(model.getAddress()); personDetailsModel.setAge(model.getAge()); personDetailsModelArrayList.add(personDetailsModel); myRealm.commitTransaction(); personDetailsAdapter.notifyDataSetChanged(); id++; }
All the operations on the database must be placed between these two statements i.e. beginTransaction() and commitTransaction().
Update Data to the Realm:
public void updatePersonDetails(PersonDetailsModel model,int position,int personID) { PersonDetailsModel editPersonDetails = myRealm.where(PersonDetailsModel.class).equalTo("id", personID).findFirst(); myRealm.beginTransaction(); editPersonDetails.setName(model.getName()); editPersonDetails.setEmail(model.getEmail()); editPersonDetails.setAddress(model.getAddress()); editPersonDetails.setAge(model.getAge()); myRealm.commitTransaction(); personDetailsModelArrayList.set(position, editPersonDetails); personDetailsAdapter.notifyDataSetChanged(); }
Delete Data to Realm:
public void deletePerson(int personId, int position) { RealmResults<PersonDetailsModel> results = myRealm.where(PersonDetailsModel.class).equalTo("id", personId).findAll(); myRealm.beginTransaction(); results.remove(0); myRealm.commitTransaction(); personDetailsModelArrayList.remove(position); personDetailsAdapter.notifyDataSetChanged(); }
Activity_Person_details.xml
Create this xml file to show the details of person when we click on any person from the main activity.
Add the code here:
<TextView android:id="@+id/tv_PersonID" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="10dp" /> <TextView android:id="@+id/tv_PersonName" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="10dp" /> <TextView android:id="@+id/tv_PersonEmail" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="10dp" /> <TextView android:id="@+id/tv_PersonAddress" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="10dp" /> <TextView android:id="@+id/tv_PersonAge" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="10dp" />
Here, it shows the TextView’s for the person name, e-mail, address, and age.
PersonDetailsActivity.java
Create this activity in our application to show the details of the person. Here, we will take the reference of all the widgets and set their properties.
Add the code in onCreate(..){..}:
tvPersonDetailId= (TextView) findViewById(R.id.tv_PersonID); tvPersonDetailName= (TextView) findViewById(R.id.tv_PersonName); tvPersonDetailEmail= (TextView) findViewById(R.id.tv_PersonEmail); tvPersonDetailAddress= (TextView) findViewById(R.id.tv_PersonAddress); tvPersonDetailAge= (TextView) findViewById(R.id.tv_PersonAge); int personID = getIntent().getIntExtra("PersonID", -1); personDetailsModel=MainActivity.getInstance().searchPerson(personID); tvPersonDetailId.setText(getString(R.string.person_id,String.valueOf(personDetailsModel.getId()))); tvPersonDetailName.setText(getString(R.string.person_name,personDetailsModel.getName())); tvPersonDetailEmail.setText(getString(R.string.person_email,personDetailsModel.getEmail())); tvPersonDetailAddress.setText(getString(R.string.person_address,personDetailsModel.getAddress())); tvPersonDetailAge.setText(getString(R.string.person_age, String.valueOf(personDetailsModel.getAge())));