Android

Android Realm : A Mobile Database

android realm database
Written by Yasir Ameen

We have heard different storage options as storing data inside android devices and all are great but Realm became a top of the list for storing data locally. Realm is a mobile database that enables us to efficiently write app’s model layer in a safe, persisted and fast way.

 

Let’s start with Android Realm

Before going into deep dive with Android Realm, lets see how easy is to insert data into database using Realm. Following picture will show you, how you can insert data into database.

 

android realm database inserting into database

 

 

Installing and Configuring Realm Into Project.

You see how easy it is, but wait here, you need to install and configure Realm database into your project before executing above code. Yeah you will need to add Realm into your project first.

 

Step 1) Create an Android Project.

Open Android Studio, create a project by selecting empty Activity and name the project what ever you like.

Step 2) Adding Realm Classpath into build.gradle File

Now open your build.gradle(Project:YourProject) file and paste the following line.

classpath "io.realm:realm-gradle-plugin:1.2.0"

 

android adding realm classpath

 

 

Step 3) Adding Realm Plugin into your build.gradle(Module:app) File.

Now open your build.gradle(Project:YourProject) file and paste the following line at top of the page and sync your project with Gradle files.

apply plugin: 'realm-android'

adding realm plugin into android studio

 

 

Creating a Realm Configuration

In order to start work with realm mechanism, we need to create RealmConfiguration. The RealmConfiguration create and saves the Realm file in your app’s file directory.

Create a class Application.java and extends it to android.app.Application and paste the following code into onCreate() Method of Application class. 

Application class? Base class for maintaining global application state.

 

   public class Application extends android.app.Application {

    @Override
    public void onCreate() {
        super.onCreate();

        RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(this)
                .name("AndroidDB.realm")
                .schemaVersion(0)
                .deleteRealmIfMigrationNeeded()
                .build();
        Realm.setDefaultConfiguration(realmConfiguration);
    }
}

 

Dont’t forget to add Application class in your manifest.xml file.


android application class realm

 

Writing Into Database Using Realm

We have installed and configure Realm database into your project, now its time to write some data into disk. In order to write data, we first create a model class which represents fields and then we begin transaction and commit transaction after setting values we want to store . Model class must be extends with RealmObject class.

 

Creating a Model Class

public class Movies extends RealmObject {


    private int id;
    private String title;
    private String release;
    private String description;
    private String director;
    private String image;
    
    public Movies() {

    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getRelease() {
        return release;
    }

    public void setRelease(String release) {
        this.release = release;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getDirector() {
        return director;
    }

    public void setDirector(String director) {
        this.director = director;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }
    
}

 

Saving Data Into Realm

After creating a model class, its time to use our model class in action, following code is the simplest form of inserting data.

public class MainActivity extends AppCompatActivity {


    private Realm realm;

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


        realm = Realm.getDefaultInstance();

        realm.beginTransaction();
        Movies movies = realm.createObject(Movies.class);
        movies.setId(1);
        movies.setTitle("Movie Title");
        movies.setDescription("Movie Description");
        movies.setDirector("Movie Director");
        movies.setRelease("Movie Release Date");
        movies.setImage("Movie Image");
        realm.commitTransaction();


    }
}

Retrieving Data From Realm

This is very common that when we store data, we also retrieve data. We received Realm Results whenever we retrieve data. Following code snippet will retrieve all the stored data. Yes we will look some advance technique later in this page.


RealmQuery<Movies> query = realm.where(Movies.class);
RealmResults<Movies> moviesResults = query.findAll();
  for(Movies result : moviesResults) {

    Toast.makeText(MainActivity.this, result.getTitle(), Toast.LENGTH_SHORT).show();
    //Similarly you can retrieve more fields.
}

Wow! how easy it is to store and retrieve data using Realm. Now Understand  more complex technique to understand more with Android Realm.

 

 

Creating And Writing Queries

So far now you know basics of Realm database that how to insert data and retrieve all as result, but there are more ways you can insert and retrieve data, so i decided to take you another step to understand more about Realm, i will also show you crud operation using Realm.

 

Writing/Adding Objects into Realm

Transaction is required in any write operations (adding, modifying and removing objects) you fire, that means you begin a transaction and commit a transaction when you want to write/modify/remove from realm.

You can write data into realm using following ways,

  • Writing objects into Realm using Begin/Commit Transaction
  • Writing objects using Transaction Block
  • Writing objects into Realm Asynchronously

 

Writing objects into Realm using Begin/Commit Transaction

You can write your objects into realm  between realm.beginTransaction() and realm.commitTransaction() method, you can see above example of saving Movies details.

// Obtain a Realm instance
Realm realm = Realm.getDefaultInstance();

realm.beginTransaction();

// write/delete/modify objects here ...

realm.commitTransaction();

 

Writing objects using Transaction Block.

You can automatically write objects into realm without keep tracking of realm.beginTransaction() and realm.commitTranscation() by using transaction block.

 


Realm realm = Realm.getDefaultInstance();

realm.executeTransaction(new Realm.Transaction() {
    @Override
    public void execute(Realm realm) {

        Movies movies = realm.createObject(Movies.class);
        movies.setId(UUID.randomUUID().toString()); // In-case your id field is Sring
        movies.setTitle(_txt_postTitle.getText().toString());
        movies.setDescription(_txt_postDesc.getText().toString());
        movies.setDirector("Director: " +_txt_postDirector.getText().toString());
        movies.setRelease("Release Date: "; +_txt_postReleaseDate.getText());
        movies.setImage(imageString);
    }
});

Writing objects into Realm Asynchronously

If you want write your objects in background thread we use “Asynchronous Transactions”, this will avoid blocking the UI thread. Using asynchronous transaction,   Realm runs transactions in background and report back when the transaction is done.

Realm realm = Realm.getDefaultInstance();

realm.executeTransactionAsync(new Realm.Transaction() {
    @Override
    public void execute(Realm bgRealm) {

        Movies movies = bgRealm.createObject(Movies.class);
        movies.setId(UUID.randomUUID().toString()); // In-case your id field is String
        movies.setTitle(_txt_postTitle.getText().toString());
        movies.setDescription(_txt_postDesc.getText().toString());
        movies.setDirector("Director: " +_txt_postDirector.getText().toString());
        movies.setRelease("Release Date: " +_txt_postReleaseDate.getText());
        movies.setImage(imageString);
    }

}, new Realm.Transaction.OnSuccess() {
    @Override
    public void onSuccess() {

        Toast.makeText(MainActivity.this, &quot;Transaction Done&quot;, Toast.LENGTH_SHORT).show();
    }

}, new Realm.Transaction.OnError() {
    @Override
    public void onError(Throwable error) {
        
        error.printStackTrace();
        Toast.makeText(MainActivity.this, &quot;Transaction Failed&quot;, Toast.LENGTH_SHORT).show();
    }
});


 

 

Reading And Querying Objects From Realm

Reading objects does not require any transaction. Objects can be accessed and queries at anytime. You can read, find and sort objects by creating queries. Let’s see the following queries.

 



//====================Fetching All Movies Stored in Realm===============
 RealmQuery<Movies> query = realm.where(Movies.class);
 RealmResults<Movies> realmResults = query.findAll();

 for(Movies results : realmResults) {

     Toast.makeText(MainActivity.this, results.getTitle(), Toast.LENGTH_SHORT).show();
     Toast.makeText(MainActivity.this, results.getDescription(), Toast.LENGTH_SHORT).show();
     //.....
 }



 
//====================Fetching All Movie Start With Letter A===============
 
 RealmQuery<Movies> query = realm.where(Movies.class);
 RealmResults<Movies> movie = query.beginsWith("title","A").findAll();
 for(Movies results : movie) {

     Toast.makeText(MainActivity.this, results.getTitle(), Toast.LENGTH_SHORT).show();
     Toast.makeText(MainActivity.this, results.getDescription(), Toast.LENGTH_SHORT).show();
     //.....
 }




 //====================Fetching a single row depending upon a query===============

 RealmQuery<Movies> query = realm.where(Movies.class);
 Movies movie = query.equalTo("title","Star Wars").findFirst();
 
 String name = movie.getTitle();
 String description = movie.getDescription();
 String director = movie.getDirector();





//====================Auto Increment===============

// In case you want to auto increment id field.
// The trick is very simple. Just check the results size
// And simple add 1 to the maximum value.
Realm realm = Realm.getDefaultInstance();

int id = -1;
RealmResults<Movies> results = realm.where(Movies.class).findAll();
if(results.size()  == 0) {

    id = 1;

} else {

     // max is an aggregate function to check maximum value
     id= results.max("id").intValue() + 1;

}

realm.beginTransaction();
Movies movies = realm.createObject(Movies.class);
movies.setId(id);
movies.setTitle("Movie Title");
movies.setDescription("Movie Description");
movies.setDirector("Movie Director");
movies.setRelease("Movie Release Date");
movies.setImage("Image Path");
realm.commitTransaction();

Toast.makeText(this, "Done with id " + id, Toast.LENGTH_SHORT).show();






//=================== Sorting Results===========================

//Sorting Objects in Ascending Order
RealmResults<Movies> results = realm.where(Movies.class).findAll().sort("title");
for(Movies result : results) {

    // Now Handle sorted objects
}

//Sorting Objects in Descending Order
RealmResults<Movies> results = realm.where(Movies.class).findAll().sort("title", Sort.DESCENDING);
for(Movies result : results) {

    // Now Handle sorted objects
}





//=================== Adding Conditions to the Result===========================

//Following Result will provide movie  with same release date
//According To the given director 
String[] director = {"Zack Snyder","Christopher Nolan","James Cameron"};
RealmResults<Movies> movie = realm.where(Movies.class).in("director",director).findAll();
RealmResults<Movies> distinctResult = movie.where().distinct("release"); // Having same release Date
for(Movies result : distinctResult) {

    // Now Handle directors objects
}

 

 

 

Updating Object From Realm.

You can update objects  by creating queries. As i mentioned above that all write operations need to be in between transaction, so first find row or the results you want to modify/update then commit all changes as transaction.

 



RealmResults<Movies> result = realm.where(Movies.class).findAll();
Movies movie = result.where().equalTo("title","Batman vs Superman").findFirst();

realm.beginTransaction();
movie.setRelease("25 March 2016");
movie.setDirector("Zack Snyder");
realm.commitTransaction();


//====================Or you can use transaction block==============================

realm.executeTransaction(new Realm.Transaction() {
    @Override
    public void execute(Realm realm) {

        RealmResults<Movies> result = realm.where(Movies.class).findAll();
        Movies movie = result.where().equalTo("title","Batman vs Superman").findFirst();
        movie.setRelease("25 March 2016");
        movie.setDirector("Zack Snyder");
       
    }
});



 

Removing and Deleting Object From Realm.

 

final RealmResults<Movies> result = realm.where(Movies.class).findAll();

realm.executeTransaction(new Realm.Transaction() {
    @Override
    public void execute(Realm realm) {

        result.deleteFirstFromRealm(); // Will Delete First Row
        result.deleteLastFromRealm(); // Will Delete Last Row
        result.deleteAllFromRealm(); // Will Delete All Objects From Realm [Clear Data]



        //=============Deleting Based on Condition==============
        Movies movie = result.where().equalTo("title","Suicide Squad").findFirst();
        movie.deleteFromRealm();
        
        
        //===========Deleting Specific Row======================

        Movies movie = result.get(4);
        movie.deleteFromRealm();

        
       
        //===============Delete All Objects From Realm============
        result.deleteAllFromRealm();
    }
});

 

 

Let’s Create an App With Realm

Now you have good understanding about Realm Database, its time to create something good with the help of Realm. We will create custom list by implementing RecyclerView. We will do the following things.

  1. Adding movie details to Realm
  2. Showing movie details in RecyclerView
  3. Deleting movies detail by clicking a delete button

 

Creating a List Item for RecyclerView

Create xml layout file in your project and name it list_item_row.xml and paste the following code. We are using cardview for representing movie details as card.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="220dp"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    android:layout_marginTop="10dp"
    >

    <android.support.v7.widget.CardView
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:cardCornerRadius="4dp"
        android:elevation="4dp">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">


            <ImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@+id/imageView"
                android:scaleType="centerCrop"
                android:src="@drawable/justice_league"
                android:layout_alignParentTop="true"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true" />

            <View
                android:layout_width="match_parent"
                android:layout_height="80dp"
                android:background="#000000"
                android:alpha="0.4"
                android:layout_alignParentBottom="true"
                android:id="@+id/view" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:text="Justice League"
                android:layout_marginTop="5dp"
                android:id="@+id/txt_title"
                android:layout_marginLeft="20dp"
                android:textColor="#ffffff"
                android:textSize="20sp"
                android:layout_alignTop="@+id/view"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:text="Fueled by his restored faith in humanity and inspired by Superman's selfless act, Bruce Wayne enlists the help of his newfound ally, Diana Prince, to face an even greater enemy."
                android:id="@+id/txt_description"
                android:ellipsize="end"
                android:textSize="12sp"
                android:layout_marginRight="15dp"
                android:textColor="#ffffff"
                android:lines="2"
                android:layout_marginLeft="20dp"
                android:layout_below="@+id/txt_title"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true" />

            <LinearLayout
                android:orientation="horizontal"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_below="@+id/txt_description"
                android:layout_alignLeft="@+id/txt_description"
                android:layout_alignStart="@+id/txt_description"
                >

                <TextView
                    android:layout_width="0dp"
                    android:text="Release Date : 17 November 2017"
                    android:textColor="#ffffff"
                    android:textSize="10sp"
                    android:gravity="center_vertical"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:id="@+id/txt_releasedate" />
                <TextView
                    android:layout_width="0dp"
                    android:text="Director: Zack Snyder"
                    android:textColor="#ffffff"
                    android:gravity="center_vertical|end"
                    android:layout_marginRight="20dp"
                    android:textSize="10sp"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:id="@+id/txt_director" />

            </LinearLayout>

            <ImageView
                android:layout_width="24dp"
                android:layout_height="24dp"
                android:id="@+id/btn_close"
                android:src="@drawable/ic_close_black_24dp"
                android:tint="#ffffff"
                android:layout_marginRight="10dp"
                android:layout_marginTop="10dp"
                android:layout_alignParentTop="true"
                android:layout_alignParentRight="true"
                android:layout_alignParentEnd="true" />
        </RelativeLayout>

    </android.support.v7.widget.CardView>

</RelativeLayout>


Output of the above xml code will look like this.

android custom list layout

 

Creating a dialog layout for adding movies.

We will add movie information using the dialog, create a layout xml file and name it add_item_dialog.xml and paste the following code.



<?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:background="#415E9B"

    android:layout_margin="8dp"
    android:orientation="vertical"
   >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >

        <android.support.v7.widget.CardView
            android:id="@+id/card_view"
            android:layout_gravity="center"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:cardCornerRadius="6dp"
            android:elevation="6dp"
            tools:ignore="UnusedAttribute">

            <LinearLayout
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                >

                <RelativeLayout
                    android:id="@+id/custom_appbar"
                    android:layout_width="match_parent"
                    android:layout_height="85dp"
                    android:background="#415E9B">


                    <LinearLayout
                        android:id="@+id/_appbar"
                        android:layout_width="match_parent"
                        android:layout_height="35dp"
                        android:layout_marginTop="4dp">

                        <ImageView
                            android:layout_width="0dp"
                            android:layout_height="20dp"
                            android:layout_gravity="center|start"
                            android:id="@+id/close_dialog"
                            android:src="@drawable/ic_close_black_24dp"
                            android:tint="#ffffff"
                            android:layout_weight="0.5"/>

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="match_parent"
                            android:text="New Movie"
                            android:textSize="16sp"
                            android:gravity="center|start"
                            android:textColor="#ffffff"
                            android:layout_weight="1"
                            android:id="@+id/robotoRegularBold"
                            tools:ignore="HardcodedText" />

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="match_parent"
                            android:text="Post"
                            android:paddingRight="14dp"
                            android:gravity="center|end"
                            android:textColor="#ffffff"
                            android:layout_weight="1"
                            tools:ignore="RtlSymmetry"
                            android:id="@+id/btn_post_d" />


                    </LinearLayout>

                    <LinearLayout

                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_below="@id/_appbar"
                        android:layout_marginTop="5dp">


                        <EditText
                            android:id="@+id/txt_title_d"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:textSize="14sp"
                            android:singleLine="true"
                            android:textCursorDrawable="@null"
                            android:layout_marginLeft="10dp"
                            android:layout_marginRight="10dp"
                            android:textColor="#ffffff"
                            android:textColorHint="#ffffff"
                            android:backgroundTint="#ffffff"
                            android:hint="Movie Title..."
                            tools:ignore="UnusedAttribute" />

                    </LinearLayout>

                </RelativeLayout>


                <LinearLayout

                    android:orientation="vertical"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"


                    >

                    <RelativeLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        >
                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:textAppearance="?android:attr/textAppearanceSmall"
                            android:text="Description"
                            android:id="@+id/textView3"
                            android:textColor="#e6000000"
                            android:layout_marginLeft="15dp"
                            android:layout_marginTop="20dp"
                            android:layout_alignParentTop="true"
                            android:layout_alignParentLeft="true"
                            android:layout_alignParentStart="true"
                            tools:ignore="HardcodedText" />

                        <EditText
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:id="@+id/txt_description_d"
                            android:layout_marginLeft="11dp"
                            android:layout_marginRight="10dp"
                            android:textSize="14sp"
                            android:lines="2"
                            android:textColorHint="#C9C9C9"
                            android:layout_marginTop="25dp"
                            android:hint="Enter Movie Description..."
                            android:layout_alignParentTop="true"
                            android:layout_alignParentLeft="true"
                            android:layout_alignParentStart="true"
                            tools:ignore="HardcodedText" />


                    </RelativeLayout>


                    <RelativeLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="10dp"
                        >
                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:textAppearance="?android:attr/textAppearanceSmall"
                            android:text="Release Date"
                            android:id="@+id/textView3"
                            android:textColor="#e6000000"
                            android:layout_marginLeft="15dp"

                            android:layout_alignParentTop="true"
                            android:layout_alignParentLeft="true"
                            android:layout_alignParentStart="true"
                            tools:ignore="HardcodedText" />

                        <EditText
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:id="@+id/txt_release_d"
                            android:layout_marginLeft="11dp"
                            android:layout_marginRight="10dp"
                            android:textSize="14sp"

                            android:lines="2"
                            android:textColorHint="#C9C9C9"
                            android:layout_marginTop="5dp"
                            android:hint="Enter Release Date..."
                            android:layout_alignParentTop="true"
                            android:layout_alignParentLeft="true"
                            android:layout_alignParentStart="true"
                            tools:ignore="HardcodedText" />


                    </RelativeLayout>

                    <RelativeLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="10dp"
                        >
                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:textAppearance="?android:attr/textAppearanceSmall"
                            android:text="Director"
                            android:id="@+id/textView3"
                            android:textColor="#e6000000"
                            android:layout_marginLeft="15dp"

                            android:layout_alignParentTop="true"
                            android:layout_alignParentLeft="true"
                            android:layout_alignParentStart="true"
                            tools:ignore="HardcodedText" />

                        <EditText
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:id="@+id/txt_director_d"
                            android:layout_marginLeft="11dp"
                            android:layout_marginRight="10dp"
                            android:textSize="14sp"

                            android:lines="2"
                            android:textColorHint="#C9C9C9"
                            android:layout_marginTop="5dp"
                            android:hint="Enter Director Name..."
                            android:layout_alignParentTop="true"
                            android:layout_alignParentLeft="true"
                            android:layout_alignParentStart="true"
                            tools:ignore="HardcodedText" />


                    </RelativeLayout>


                    <RelativeLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="10dp"
                        >
                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:textAppearance="?android:attr/textAppearanceSmall"
                            android:text="Add Image"
                            android:id="@+id/textView3"
                            android:textColor="#e6000000"
                            android:layout_marginLeft="15dp"

                            android:layout_alignParentTop="true"
                            android:layout_alignParentLeft="true"
                            android:layout_alignParentStart="true"
                            tools:ignore="HardcodedText" />
                        <ImageView
                            android:layout_width="match_parent"
                            android:layout_height="120dp"
                            android:scaleType="centerInside"
                            android:src="@drawable/add_more"
                            android:layout_marginTop="25dp"
                            android:layout_marginLeft="40dp"
                            android:layout_marginRight="40dp"
                            android:id="@+id/img_movie" />

                    </RelativeLayout>

                </LinearLayout>
            </LinearLayout>
        </android.support.v7.widget.CardView>

    </LinearLayout>

</LinearLayout>
 

Output of the following code will be look like this,

android realm adding data

 

Writing Adapter Class for Movies

Create a java file in your project and name it MoviesAdapter.javathis class will be responsible for showing our data as a List Item using RecyclerView. 

Please see code very closely that we also implemented delete functionality if someone click the cross icon place at the top right corner of card.

 

public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.myViewHolder> {


    private Realm realm;
    private List<Movies> moviesList;
    private final LayoutInflater inflater;
    private Context context;

    public MoviesAdapter(Context context){
        inflater = LayoutInflater.from(context);
        this.context = context;
        realm = Realm.getDefaultInstance();

        moviesList = new ArrayList<>();


        //Querying All Movies Stored in Realm
        RealmQuery<Movies> query = realm.where(Movies.class);
        RealmResults<Movies> realmResults = query.findAll();

        for(Movies results : realmResults) {

                moviesList.add(results);
        }

    }

    @Override
    public MoviesAdapter.myViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = inflater.inflate(R.layout.list_item_row,parent,false);
        myViewHolder holder = new myViewHolder(view);

        return holder;
    }

    @Override
    public void onBindViewHolder(MoviesAdapter.myViewHolder holder, final int position) {

        final Movies movies = moviesList.get(position);

        holder._title.setText(movies.getTitle());
        holder._desc.setText(movies.getDescription());
        holder._releaseDate.setText(movies.getRelease());
        holder._director.setText(movies.getDirector());
        Glide.with(context).load(movies.getImage()).crossFade().centerCrop().into(holder._imgview);

        holder._close_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {



                //Set Message and Title
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setMessage("Do you really want to remove from the database?.")
                        .setTitle("Are you sure?");

                //Set When SEND Button Click
                builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                        Movies _movies = moviesList.get(position);
                        realm.beginTransaction();
                        Movies currentMovies = realm.where(Movies.class).equalTo("id",_movies.getId()).findFir
                        currentMovies.deleteFromRealm();;
                        realm.commitTransaction();
                        moviesList.remove(position);
                        notifyDataSetChanged();
                    }
                });

                //Set When Cancel Button Click
                builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                        //Dismissing the alertDialog
                        dialogInterface.dismiss();
                    }
                });

                AlertDialog dialog = builder.create();
                dialog.show();



            }
        });

    }

    @Override
    public int getItemCount() {
        return moviesList.size();
    }

    public class myViewHolder extends RecyclerView.ViewHolder {

        ImageView _imgview;
        ImageView _close_btn;
        TextView _title;
        TextView _desc;
        TextView _releaseDate;
        TextView _director;

        public myViewHolder(View itemView) {
            super(itemView);

            _imgview = (ImageView) itemView.findViewById(R.id.imageView);
            _title = (TextView) itemView.findViewById(R.id.txt_title);
            _desc = (TextView) itemView.findViewById(R.id.txt_description);
            _releaseDate = (TextView) itemView.findViewById(R.id.txt_releasedate);
            _director = (TextView) itemView.findViewById(R.id.txt_director);
            _close_btn = (ImageView) itemView.findViewById(R.id.btn_close);
        }
    }
}

 

 

Putting it All Together

Ok so you have created a list_item_layout, custom dialog and written Adapter for you RecyclerView, Now its time to put it all together.

Open MainActivity.java  and paste the following code and don’t forget add ListView in your activity_main.xml file.


public class MainActivity extends AppCompatActivity {


    private static final int REQUEST_CODE_PICKER = 1000;
    private Realm realm;
    private AlertDialog dialog;
    private ArrayList<Image> images;
    private String imageString = "";
    ImageView _movie_image;
    MoviesAdapter adpater;

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

        refreshDataSet();
        

    }

    private void refreshDataSet() {
        adpater = new MoviesAdapter(MainActivity.this);
        RecyclerView rview = (RecyclerView) findViewById(R.id.my_recycler_view);
        rview.setItemAnimator(new DefaultItemAnimator());
        rview.setAdapter(adpater);
        rview.setLayoutManager(new LinearLayoutManager(MainActivity.this));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.add:
                showAddMovieDialog();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }



    private void showAddMovieDialog() {

        final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        LayoutInflater inflater = getLayoutInflater();

        final View dialog_layout = inflater.inflate(R.layout.add_item_dialog,null);
        builder.setView(dialog_layout);

        final EditText _txt_postTitle = (EditText) dialog_layout.findViewById(R.id.txt_title_d);
        final EditText _txt_postDesc = (EditText) dialog_layout.findViewById(R.id.txt_description_d);
        final EditText _txt_postReleaseDate = (EditText) dialog_layout.findViewById(R.id.txt_release_d);
        final EditText _txt_postDirector = (EditText) dialog_layout.findViewById(R.id.txt_director_d);
        TextView _btn_post = (TextView) dialog_layout.findViewById(R.id.btn_post_d);
        ImageView _dialog_close = (ImageView) dialog_layout.findViewById(R.id.close_dialog);
         _movie_image = (ImageView) dialog_layout.findViewById(R.id.img_movie);



        _movie_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                ImagePicker.create(MainActivity.this)
                        .folderMode(true)
                        .single()
                        .showCamera(true)
                        .limit(1)
                        .origin(images)
                        .start(REQUEST_CODE_PICKER);
            }
        });
         _btn_post.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View view) {

                 //Retrieving Id of last inserted Item

                 RealmResults<Movies> query = realm.where(Movies.class).findAll();
                 int nextID = query.size(); //Retrieving a results size.

                 realm.beginTransaction();


                 Movies movies = realm.createObject(Movies.class);
                 movies.setId(nextID + 1);
                 movies.setTitle(_txt_postTitle.getText().toString());
                 movies.setDescription(_txt_postDesc.getText().toString());
                 movies.setDirector("Director: " +_txt_postDirector.getText().toString());
                 movies.setRelease("Release Date: " +_txt_postReleaseDate.getText());
                 movies.setImage(imageString);
                 realm.commitTransaction();
                 dialog.dismiss();
                 refreshDataSet();

             }
         });

        
        _dialog_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                dialog.dismiss();
            }
        });


        dialog = builder.create();
        dialog.show();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK) {

            switch (requestCode) {

                case REQUEST_CODE_PICKER:

                    images = data.getParcelableArrayListExtra(ImagePickerActivity.INTENT_EXTRA_SELECTED_IMAGES);
                    try
                    {

                        String holderOne = images.get(0).getPath();
                        imageString = holderOne;
                        Glide.with(this).load(holderOne).centerCrop().crossFade().into(_movie_image);
                    }
                    catch(Exception e)
                    {
                        Log.e("MyActivity", e.getMessage());
                    }
                    break;
            }
        }
    }
}

 

Run the app and see the results like the following image.

android custom dialog inserting into realmandroid recycler viewandroid deleting data from realm

About the author

Yasir Ameen

I'm a programmer, teacher, and speaker. I work out of my home in Pakistan, Karachi for the Mobile, especially Android Platform. I discuss about technology, gadgets, codes, the devices we’re going and we’ve been. I’m excited about community, social equity, and media.

5 Comments

Leave a Comment