Android working with Realm Database

A realm is an open-source database that can be used to store data locally in android. Realm Mobile Database is an alternative to SQLite and Core Data in your Android projects.

The realm runs directly inside phones, tablets. It’s a lightweight database in Mobile Development, realm takes very less memory space compared to SQLite.

Realm also allows us to write data in UI thread. it’s Support Cross-platform (Use the same database for all your apps, on any major platform. like Android, objective c, JavaScript, Swift, Xamarin).

  • Realm
    is our equivalent of a database, Realm is not a table. Realm not stores Data in Table and column. But a Realm can contain multiple kinds of objects, and map to one file on disk.
  • Realm
    has Support JSON Data or Object.
  • Realm supports the following field types: boolean, byte, short, int, long, float, double, String, Date. Moreover, subclasses of RealmObject and RealmList<? extends RealmObject> support model relationships.
  • it’s a NoSQL database.
  • Realm supports easy thread-safety, relationships & encryption.

Prerequisites :

  • The realm is supported in Android only, not available for Java at the moment.
  • Android Studio version 0.8.6
  • JDK version 7
  • Android API Level minimum 9 (Android 2.3 Gingerbread).

Adding the Realm to a Project:

Go to project level build.gradle file and add the following line under dependencies section.

classpath “io.realm:realm-gradle-plugin:3.0.0”

Now go to app-level build.gradle file and add the following line at the top.

apply plugin: ‘realm-android’

Sync your project.

To use Realm in an Android project, you need to add it as a compile dependency in the app module’s build.gradle file.

buildscript {
repositories {
jcenter()
}
dependencies {
classpath "io.realm:realm-gradle-plugin:3.7.2"
}
}

Write all operation for Note Notes like Create, Update, Delete, Retrieve Notes and Text from Realm DataBase

RealmManipulator.java

public class RealmManipulator {

    private static RealmManipulator dbManager;

    private static Realm realm;

    private String realmName = "RealmNote";

    private RealmManipulator(Context context) {

        if (realm == null) {

            //Realm Object is Created

            Realm.init(context);

            RealmConfiguration configuration = new RealmConfiguration.Builder()

                    .name(realmName)

                    .deleteRealmIfMigrationNeeded()

                    .build();

            realm = Realm.getInstance(configuration);

        }

    }

    public static RealmManipulator getRealmInstance(Context context) {

        if (dbManager == null) {

            //DBManager Object is Created

            dbManager = new RealmManipulator(context);

        }

        return dbManager;

    }

    //Note Added in Realm

    public void addOrUpdateRealmList(StickyNote note) {

        realm.beginTransaction();

        realm.copyToRealmOrUpdate(note);

        realm.commitTransaction();

    }

    //Get Realm Data

    public RealmResults getAllStickyNotes() {

        realm.beginTransaction();

        RealmResults realmNotes = realm.where(StickyNote.class).findAll();

        realm.commitTransaction();

        return realmNotes;

    }

    //Realm Data Updated

    public void updateStickyNote(StickyNote note) {

        realm.beginTransaction();

        realm.copyToRealmOrUpdate(note);

        realm.commitTransaction();

    }

    //Realm Data Deleted

    public void deleteStickyNote(StickyNote note) {

        realm.beginTransaction();

        note.deleteFromRealm();

        realm.commitTransaction();

    }

}

StickyHome.java

public class StickyHome extends AppCompatActivity {

 RealmResults<StickyNote> realmNotes;
 RecyclerView recyclerView;
 TextView text_noitem;
 Button button_blog,button_app;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_sicky_home);
 Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

 setSupportActionBar(toolbar);
 text_noitem=(TextView)findViewById(R.id.text_noitem);
 button_blog=(Button)findViewById(R.id.button_blog);
 button_app=(Button)findViewById(R.id.button_app);


 FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
 fab.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View view) {
 Intent i = new Intent(getApplicationContext(), NewStickyNoteActivity.class);
 startActivity(i);
 finish();
 }
 });

 recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
 realmNotes = RealmManipulator.getRealmInstance(getApplicationContext()).getAllStickyNotes();

 if (realmNotes.size() != 0) {
 text_noitem.setVisibility(View.GONE);
 setAdapter(realmNotes);
 } else {
 text_noitem.setVisibility(View.VISIBLE);
 Toast.makeText(getApplicationContext(), "There are Nothing to Show", Toast.LENGTH_LONG).show();

 }

 button_app.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {
 final String appPackageName = getPackageName(); // getPackageName() from Context or Activity object
 try {
 startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" +"com.abhay.androidtutorial")));
 } catch (android.content.ActivityNotFoundException anfe) {
 startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + "com.abhay.androidtutorial")));
 }
 }
 });


 button_blog.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {
 String url = "http://www.geekcodehub.com/";
 Intent i = new Intent(Intent.ACTION_VIEW);
 i.setData(Uri.parse(url));
 startActivity(i);
 }
 });

 }
 public void setAdapter(List<StickyNote> noteList) {
 LinearLayoutManager llm = new LinearLayoutManager(getApplicationContext());
 recyclerView.setHasFixedSize(true);
 recyclerView.setLayoutManager(llm);

 RVAdapter rvAdapter = new RVAdapter(noteList, getApplicationContext());
 recyclerView.setAdapter(rvAdapter);
 }

 @Override
 protected void onResume() {
 super.onResume();

 realmNotes = RealmManipulator.getRealmInstance(getApplicationContext()).getAllStickyNotes();
 setAdapter(realmNotes);

 if (realmNotes.size() != 0) {
 text_noitem.setVisibility(View.GONE);
 setAdapter(realmNotes);
 } else {
 text_noitem.setVisibility(View.VISIBLE);
 Toast.makeText(getApplicationContext(), "There are Nothing to Show", Toast.LENGTH_LONG).show();
 }
 }
}

activity_sicky_home.xml

<?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"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:background="#d3d3d3"
 tools:context="abhay.com.mystickynotes.activity.StickyHome">

 <android.support.design.widget.AppBarLayout
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:id="@+id/app"
 android:theme="@style/AppTheme.AppBarOverlay">

 <android.support.v7.widget.Toolbar
 android:id="@+id/toolbar"
 android:layout_width="match_parent"
 android:layout_height="?attr/actionBarSize"
 android:background="?attr/colorPrimary"
 app:popupTheme="@style/AppTheme.PopupOverlay" >


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

 </android.support.design.widget.AppBarLayout>

 <LinearLayout
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:layout_below="@+id/app" >

 <include layout="@layout/content_sicky_home" />

 </LinearLayout>

 <android.support.design.widget.FloatingActionButton
 android:id="@+id/fab"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_gravity="bottom|end"
 android:layout_alignParentRight="true"
 android:layout_alignParentBottom="true"
 android:layout_marginRight="@dimen/fab_margin"
 android:layout_marginLeft="@dimen/fab_margin"
 android:layout_marginBottom="@dimen/fab_margin_top"
 app:backgroundTint="@color/colorPrimary"
 app:srcCompat="@drawable/add" />

</RelativeLayout>

NewStickyNoteActivity.java

public class NewStickyNoteActivity extends AppCompatActivity {

    EditText etTitle, etContent;
    Button btnSave;

    StickyNote stickyNote;
    Button button_blog,button_app;

    int id=0;

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

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setLogo(R.drawable.logo);

        button_blog=(Button)findViewById(R.id.button_blog);
        button_app=(Button)findViewById(R.id.button_app);
        etTitle = (EditText) findViewById(R.id.etTitle);
        etContent = (EditText) findViewById(R.id.etContent);

        btnSave = (Button) findViewById(R.id.btn_save);

        final StickyNote parcelableStickyNote = getIntent().getParcelableExtra("StickyNoteData");
        if(parcelableStickyNote != null) {
            etTitle.setText(parcelableStickyNote.getNoteTitle());
            etContent.setText(parcelableStickyNote.getNoteContent());
            etTitle.setSelection(etTitle.getText().length());
            btnSave.setText("Update Note");
        }

        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String title = etTitle.getText().toString();
                String content = etContent.getText().toString();

                if(title.equals("") && content.equals("")){
                    Snackbar.make(v, "Plese Enter Title and Content", Snackbar.LENGTH_LONG)
                            .setAction("Action", null).show();
                }
                else {

                    if(btnSave.getText().equals("Update Note")){
                        parcelableStickyNote.setNoteTitle(etTitle.getText().toString());
                        parcelableStickyNote.setNoteContent(etContent.getText().toString());
                        RealmManipulator.getRealmInstance(getApplicationContext()).updateStickyNote(parcelableStickyNote);
                        finish();
                    }
                    else {

                        RealmResults<StickyNote> realmNotes = RealmManipulator.getRealmInstance(getApplicationContext()).getAllStickyNotes();
                        if (realmNotes.size() != 0)
                            id = realmNotes.last().getId();

                        stickyNote = new StickyNote();
                        stickyNote.setId(id + 1);
                        stickyNote.setNoteTitle(etTitle.getText().toString());
                        stickyNote.setNoteContent(etContent.getText().toString());

                        RealmManipulator.getRealmInstance(getApplicationContext()).addOrUpdateRealmList(stickyNote);

                    Intent i = new Intent(getApplicationContext(),StickyHome.class);
                    startActivity(i);
                        finish();
                    }
                }
            }
        });



        button_app.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String appPackageName = getPackageName(); // getPackageName() from Context or Activity object
                try {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" +"com.abhay.androidtutorial")));
                } catch (android.content.ActivityNotFoundException anfe) {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + "com.abhay.androidtutorial")));
                }
            }
        });


        button_blog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = "http://www.geekcodehub.com/";
                Intent i = new Intent(Intent.ACTION_VIEW);
                i.setData(Uri.parse(url));
                startActivity(i);
            }
        });
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

            switch (item.getItemId()) {
                // Respond to the action bar's Up/Home button
                case android.R.id.home:
                    NavUtils.navigateUpFromSameTask(this);
                    return true;
            }
        return super.onOptionsItemSelected(item);

    }
}

activity_new_sticky_note.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context="abhay.com.mystickynotes.activity.NewStickyNoteActivity"
    android:background="#D3d3d3">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="10dp"
        android:id="@+id/ui"
        android:layout_margin="10dp"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:background="@color/colorPrimary">

        <EditText
            android:layout_width="300dp"
            android:layout_height="wrap_content"
            android:id="@+id/etTitle"
            android:hint="Enter your Title"
            android:textSize="30sp"
            android:textColorHint="@android:color/holo_red_dark"
            android:textColor="@android:color/white"
            android:textStyle="bold"
            android:layout_marginTop="20dp"
            android:layout_gravity="center" />

        <EditText
            android:id="@+id/etContent"
            android:layout_width="300dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginBottom="20dp"
            android:layout_marginTop="20dp"
            android:gravity="top|left"
            android:hint="Enter your Content"
            android:inputType="textMultiLine"
            android:lines="4"
            android:maxLines="10"
            android:minLines="6"
            android:scrollbars="vertical"
            android:textColor="@android:color/white"
            android:textColorHint="@android:color/black"
            android:textSize="20sp" />


        <RelativeLayout
            android:layout_width="110dp"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_below="@+id/ui"
            android:layout_marginTop="20dp"
            android:background="@color/bg_screen3"
            android:gravity="center"
            android:layout_centerVertical="true"
            android:layout_alignEnd="@+id/ui">

            <Button
                android:layout_width="100dp"
                android:layout_height="wrap_content"
                android:id="@+id/btn_save"
                android:text="Save Note"
                android:textColor="@android:color/white"
                android:background="@color/oranged"
                android:layout_alignParentTop="true"
                android:layout_alignParentStart="true" />

        </RelativeLayout>


    </LinearLayout>
    <Button
        android:id="@+id/button_blog"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_margin="10dp"
        android:textStyle="bold"
        android:textColor="@android:color/white"
        android:background="@android:color/holo_red_dark"
        android:text="Geek Code Hub Android Tutorial Blog"
        android:layout_alignParentBottom="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentEnd="true" />
    <Button
        android:id="@+id/button_app"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_margin="10dp"
        android:textStyle="bold"
        android:background="@android:color/white"
        android:text="Geek Code Hub Android Tutorial app"
        android:layout_above="@+id/button_app"
        android:layout_alignParentStart="true"
        android:layout_marginBottom="17dp" />


</LinearLayout>

RVAdapter.java

public class RVAdapter extends RecyclerView.Adapter<RVAdapter.DataViewHolder> {

    List<StickyNote> stickyNotesList;
    StickyNote stickyNoteBackup;
    Context context;

    public RVAdapter(List<StickyNote> stickyNotesList, Context context) {
        this.stickyNotesList = stickyNotesList;
        this.context = context;
    }

    @Override
    public DataViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.sticky_note_row,parent,false);
        DataViewHolder dataViewHolder = new DataViewHolder(view);
        return dataViewHolder;
    }

    @Override
    public void onBindViewHolder(DataViewHolder holder, int position) {
        holder.textTitle.setText(stickyNotesList.get(position).getNoteTitle());
       // holder.textContent.setText(stickyNotesList.get(position).getNoteContent());
    }

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

    public class DataViewHolder extends RecyclerView.ViewHolder {

        ImageView noteIcon;
        ImageButton update, delete;
        TextView textTitle, textContent;

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

            textTitle = (TextView) itemView.findViewById(R.id.txt_title);
            //textContent = (TextView) itemView.findViewById(R.id.txt_content);

            update = (ImageButton) itemView.findViewById(R.id.update);
            delete = (ImageButton) itemView.findViewById(R.id.delete);

            update.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    StickyNote stickyNote = stickyNotesList.get(getAdapterPosition());
                    Intent i = new Intent(context, NewStickyNoteActivity.class);
                    i.putExtra("StickyNoteData", stickyNote);
                    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(i);
                    notifyDataSetChanged();
                }
            });

            delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final StickyNote stickyNote = stickyNotesList.get(getAdapterPosition());

                    stickyNoteBackup = new StickyNote(stickyNote.getId(),stickyNote.getNoteTitle(),stickyNote.getNoteContent());

                    RealmManipulator.getRealmInstance(context).deleteStickyNote(stickyNote);

                    notifyDataSetChanged();

                    Snackbar snackbar = Snackbar.make(v, "Note is Deleted", Snackbar.LENGTH_LONG)
                            .setAction("UNDO DELETE", new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    RealmManipulator.getRealmInstance(context).updateStickyNote(stickyNoteBackup);
                                    notifyDataSetChanged();
                                    Snackbar snackbar1 = Snackbar.make(view, "Note is Restored!", Snackbar.LENGTH_SHORT);
                                    snackbar1.show();
                                }
                            });

                    snackbar.show();
                }
            });

        }
    }
}

res/layout/sticky_note_row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.CardView
        android:id="@+id/cv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="5dp"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginTop="5dp"
        card_view:cardBackgroundColor="@android:color/black">

        <LinearLayout
            android:id="@+id/rl"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginBottom="5dp"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp"
            android:layout_marginTop="5dp"
            android:background="@color/colorPrimary">

            <RelativeLayout
                android:id="@+id/ll"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_toRightOf="@+id/sticky_icon"
                android:orientation="horizontal">

                <TextView
                    android:id="@+id/txt_title"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentTop="true"
                    android:layout_margin="10dp"
                    android:layout_marginLeft="15dp"
                    android:maxLength="15"
                    android:text="Your Title"
                    android:textColor="@android:color/white"
                    android:textSize="20sp"
                    android:textStyle="bold|italic" />


                <ImageButton
                    android:id="@+id/update"
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:layout_alignParentEnd="true"
                    android:layout_alignParentTop="true"
                    android:layout_marginEnd="12dp"
                    android:layout_marginRight="10dp"
                    android:background="@drawable/pencil" />

                <ImageButton
                    android:id="@+id/delete"
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:layout_alignParentTop="true"
                    android:layout_marginRight="10dp"
                    android:layout_toStartOf="@+id/update"
                    android:background="@drawable/delete" />
            </RelativeLayout>
        </LinearLayout>

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

</LinearLayout>

StickyNote.java

public class StickyNote extends RealmObject implements Parcelable {

    @PrimaryKey
    private int id;
    private String noteTitle, noteContent;


    public int getId() {
        return id;
    }

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

    public String getNoteTitle() {
        return noteTitle;
    }

    public void setNoteTitle(String noteTitle) {
        this.noteTitle = noteTitle;
    }

    public String getNoteContent() {
        return noteContent;
    }

    public void setNoteContent(String noteContent) {
        this.noteContent = noteContent;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(this.id);
        dest.writeString(this.noteTitle);
        dest.writeString(this.noteContent);
    }

    public StickyNote() {
    }

    public StickyNote(int id, String noteTitle, String noteContent) {
        this.id = id;
        this.noteTitle = noteTitle;
        this.noteContent = noteContent;
    }

    protected StickyNote(Parcel in) {
        this.id = in.readInt();
        this.noteTitle = in.readString();
        this.noteContent = in.readString();
    }

    public static final Parcelable.Creator<StickyNote> CREATOR = new Parcelable.Creator<StickyNote>() {
        @Override
        public StickyNote createFromParcel(Parcel source) {
            return new StickyNote(source);
        }

        @Override
        public StickyNote[] newArray(int size) {
            return new StickyNote[size];
        }
    };
}