Realm database replacing sqlite in android

In the last article we have learned about the database wrapper Green Dao that the best ORM for android application. If you have not read this article before, please check here Green Dao.

Android provides base component for storing data into database is SQLite. It is based on sql query based. So it will make our code lengthy and difficult to used in large app.  Green Dao is ORM based wrapper for Android database, but some how it also not completed to catch all minds.

Now Realm came into market for runtime database. The best thing realm is that can be used many platform like Android, iOS, Java etc. It is based on ORM realm Object basis. Its easy to use and easy to manage any of project.

In this article I am showing to add any object Item into database table and retrieve those objects and show on recyclerView by using realm. And if it is required to delete from realm then delete them.
Here is uploaded video that helps to understand the realm feature and what is am focusing in this article.


Thanks for watching this video. Lets create a sample android app to achieve this.

build.gradle project level

    
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.2'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
        classpath "io.realm:realm-gradle-plugin:2.2.1"   
         // this is the realm plugin you need to add this dependency in project level as I added
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

build.gradle app level

    
apply plugin: 'realm-android'
// Add this plugin on top of your plugin listed.

MainApplication.java

 
import android.app.Application;

import io.realm.Realm;
import io.realm.RealmConfiguration;

/**
 * Created by sunil on 12/14/16.
 */

public class MainApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        // Initialize Realm. Should only be done once when the application starts.
        Realm.init(this);
    }
} 

Note.java

  
 public class Note extends RealmObject {

    private long id;
    private String tittle;
    private String comment;
    private String noteDate;

    public long getId() {
        return id;
    }

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

    public String getTittle() {
        return tittle;
    }

    public void setTittle(String tittle) {
        this.tittle = tittle;
    }

    public String getComment() {
        return comment;
    }

    public void setComment(String comment) {
        this.comment = comment;
    }

    public String getNoteDate() {
        return noteDate;
    }

    public void setNoteDate(String noteDate) {
        this.noteDate = noteDate;
    }
 }

NoteManager.java

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

import io.realm.Realm;
import io.realm.RealmQuery;
import io.realm.RealmResults;

/**
 * Created by sunil on 12/14/16.
 */

public class NoteManager {

    public static void addNote(Realm realm, Note noteData){
        realm.beginTransaction();
        Note note = realm.createObject(Note.class);
        note.setId(getCount(realm)+1);
        note.setTittle(noteData.getTittle());
        note.setComment(noteData.getComment());
        note.setNoteDate(noteData.getNoteDate());
        realm.commitTransaction();
    }

    public static List getAllNotes(Realm realm){
        List noteList = new ArrayList<>();
        RealmQuery query = realm.where(Note.class);
        RealmResults results = query.findAll();
        for (int index =0; index < results.size(); index++){
            Note note = results.get(index);
            noteList.add(note);
        }
        return noteList;

    }

    public static Note getNoteByID( Realm realm , long id){
        Note note = realm.where(Note.class).equalTo("id", id).findFirst();
        return note;
    }

    private static long getCount(Realm realm){
        long count = realm.where(Note.class).count();
        return count;
    }

    public static void updateNote(Realm realm, Note noteData){

       Note note = realm.where(Note.class).equalTo("id", noteData.getId()).findFirst();
        realm.beginTransaction();
        note.setTittle(noteData.getTittle());
        note.setComment(noteData.getComment());
        note.setNoteDate(noteData.getNoteDate());
        realm.commitTransaction();
    }


    public static void deleteNote(Realm realm, final Long id){
        realm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                RealmResults result = realm.where(Note.class).equalTo("id", id).findAll();
                result.deleteAllFromRealm();
            }
        });
    }
}

MainActivity.java

    
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

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

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.realm.Realm;

public class MainActivity extends AppCompatActivity implements NoteAdapter.OnInteractionDelete{

    @BindView(R.id.no_data)
    TextView noData;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.button_create)
    Button buttonCreate;
    @BindView(R.id.activity_main)
    RelativeLayout activityMain;

    Realm realm;
    NoteAdapter adapter;

    private List list ;

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

        realm = Realm.getDefaultInstance();

        recyclerView.setLayoutManager(new LinearLayoutManager(this));
    }


    @Override
    protected void onResume() {
        super.onResume();
        list = new ArrayList<>();
        list = NoteManager.getAllNotes(realm);
        if (list == null && list.size() == 0) {
            noData.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.GONE);
        } else {
            noData.setVisibility(View.GONE);
            recyclerView.setVisibility(View.VISIBLE);
            adapter = new NoteAdapter(this, list, this);
            recyclerView.setAdapter(adapter);

        }
    }

    @OnClick(R.id.button_create)
    public void createNoteClick() {
        Intent intent = new Intent(MainActivity.this, NoteDetailActivity.class);
        intent.putExtra("Create", true);
        startActivity(intent);
    }

    @Override
    public void onDeleteClick(final int position) {
        Note note = list.get(position);
        Long id = note.getId();
        NoteManager.deleteNote(realm, id);
        list.remove(note);
        adapter.notifyItemRemoved(position);
        adapter.notifyItemRangeChanged(position, adapter.getItemCount());
    }
}

activity_main.xml

    
<?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:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.sunil.realmandroidapp.MainActivity">

    <TextView
        android:id="@+id/no_data"
        android:text="@string/no_note"
        android:layout_centerInParent="true"
        android:gravity="center"
        android:visibility="gone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

   <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_marginBottom="20dp"
        android:layout_height="wrap_content">
   </android.support.v7.widget.RecyclerView>

   <Button
        android:id="@+id/button_create"
        android:layout_alignParentBottom="true"
        android:background="@color/colorPrimary"
        android:layout_width="match_parent"
        android:text="@string/Create_Note"
        android:textColor="#ffff"
        android:layout_height="wrap_content" />
</RelativeLayout>

NoteDetailActivity.java

    
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.EditText;

import java.util.Calendar;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.realm.Realm;

/**
 * Created by sunil on 12/14/16.
 */

public class NoteDetailActivity extends AppCompatActivity {

    @BindView(R.id.title)
    EditText title;
    @BindView(R.id.titleLayout)
    TextInputLayout titleLayout;
    @BindView(R.id.description)
    EditText description;
    @BindView(R.id.descriptionLayout)
    TextInputLayout descriptionLayout;
    @BindView(R.id.age)
    EditText dateEditText;
    @BindView(R.id.dateLayout)
    TextInputLayout dateLayout;
    @BindView(R.id.save)
    Button save;

    Realm realm;

    private boolean isCreate;
    private Long noteId;
    private Note mNote;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_note_detail);
        ButterKnife.bind(this);

        realm = Realm.getDefaultInstance();

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            isCreate = bundle.getBoolean("Create");
            noteId = bundle.getLong("NoteID");
        }
        if (!isCreate) {
            save.setText("Save");
            mNote = NoteManager.getNoteByID(realm, noteId);
            if (mNote != null) {
                title.setText(mNote.getTittle());
                description.setText(mNote.getComment());
                dateEditText.setText(mNote.getNoteDate() + "");
            }
        } else {
            save.setText("Add");
            Calendar c = Calendar.getInstance();
            System.out.println("Current time => " + c.getTime());
            dateEditText.setText(c.getTime()+"");
        }
    }

    @OnClick(R.id.save)
    public void saveClick(){
        if (isCreate){
            // insert note
            if (!valid()){
                return;
            }else{
                Note note = new Note();
                note.setTittle(title.getText().toString());
                note.setComment(description.getText().toString());
                note.setNoteDate(dateEditText.getText().toString());
                NoteManager.addNote(realm, note);
                finish();
            }

        }else{
            // update note
            if (!valid()){
                return;
            }else{
                mNote.setTittle(title.getText().toString());
                mNote.setComment(description.getText().toString());
                mNote.setNoteDate(dateEditText.getText().toString());
                NoteManager.updateNote(realm, mNote);
                finish();
            }
        }
    }

    private boolean valid(){
        boolean isValid;
        if (Utility.nullCheck(titleLayout, "Title")){
            isValid = false;
        }
        else if (Utility.nullCheck(descriptionLayout, "Comment")){
            isValid = false;
        }
        else if (Utility.nullCheck(dateLayout, "Date")){
            isValid = false;
        }else{
            isValid = true;
        }
        return  isValid;
    }
}

activity_note_detail.xml

    
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="8dp">

   <android.support.design.widget.TextInputLayout
        android:id="@+id/titleLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp">

       <EditText
            android:id="@+id/title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="Title"/>
    </android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout
        android:id="@+id/descriptionLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/titleLayout"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp">

       <EditText
            android:id="@+id/description"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="Comment"/>
   </android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout
        android:id="@+id/dateLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/descriptionLayout"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp">

        <EditText
            android:id="@+id/age"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="Date"/>
  </android.support.design.widget.TextInputLayout>

    <Button
        android:id="@+id/save"
        android:text="@string/add"
        android:background="@color/colorPrimary"
        android:textColor="#fff"
        android:layout_alignParentBottom="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</RelativeLayout>

NoteAdapter.java

    
import android.app.Activity;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by sunil on 12/14/16.
 */

public class NoteAdapter extends RecyclerView.Adapter {

    private List noteList;
    private Context context;
    OnInteractionDelete mListener;

    public NoteAdapter(Context context, List notes, Activity activity) {
        this.noteList = notes;
        this.context = context;
        this.mListener = (OnInteractionDelete) activity;
    }

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

    @Override
    public void onBindViewHolder(NoteViewHolder noteViewHolder, final int i) {
        Note note = noteList.get(i);
        noteViewHolder.title.setText(note.getTittle());
        noteViewHolder.description.setText(note.getComment());
        noteViewHolder.date.setText(note.getNoteDate()+"");
        noteViewHolder.delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mListener.onDeleteClick(i);
            }
        });
    }

    @Override
    public NoteViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item_note, viewGroup, false);
        return new NoteViewHolder(itemView);
    }

    public static class NoteViewHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.title)
        TextView title;
        @BindView(R.id.description)
        TextView description;
        @BindView(R.id.date)
        TextView date;
        @BindView(R.id.delete)
        ImageView delete;


        public NoteViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    public interface OnInteractionDelete{
        void onDeleteClick(int position);
    }
}

list_item_note.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"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="8dp">

    <android.support.v7.widget.CardView
        android:id="@+id/cardView"
        app:cardUseCompatPadding="true"
        app:cardCornerRadius="0dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <RelativeLayout
            android:id="@+id/main_container"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="5dp">

           <TextView
                android:id="@+id/title"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textStyle="bold"
                android:textSize="16sp"
                android:layout_marginBottom="3dp"
                android:text="@string/title"/>

            <ImageView
                android:id="@+id/delete"
                android:src="@drawable/ic_delete_black_24dp"
                android:layout_alignParentRight="true"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            <TextView
                android:id="@+id/description"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/delete"
                android:textSize="13sp"
                android:text="@string/comment"/>

           <TextView
                android:id="@+id/date"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/delete"
                android:textSize="13sp"
                android:gravity="right"
                android:text="@string/date"/>

       </RelativeLayout>


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

</RelativeLayout>



Thanks for reading this article. I hope it will help you to understand.

No comments:

Post a Comment

Debug Database in Android

In my last tutorial, we have learned how we can use persistence database in android. We also understood which database wrapper we can use...

Contact Me

Name

Email *

Message *