Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Integrate Realm in android application

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 49
    Comment on it

    What is Realm?

    We all are aware of SQLite for internal storage in android but now we can use Realm as SQLite replacement.
    Realm has become popular for being a database with its own C++ core. It’s not just an alternative for SQLite, but much easier and faster than it as well. Also, it provides the way for data access from multiple languages.

    Integration of Realm in an android application:

    Step 1: Open project level build.gradle file and add the following realm classpath dependency.

    dependencies {
            classpath 'io.realm:realm-gradle-plugin:2.2.1'
        }

    Step 2: Open module/application level build.gradle file and add the following plugin at the top of the file.

    apply plugin: 'realm-android'

    Step 3: Now call Realm.init(Context) method, before calling any other method of Realm api.

    import io.realm.Realm;
    
    public class BaseApplication extends Application {
        @Override
        public void onCreate(){
            super.onCreate();
            Realm.init(this);
        }
    }
    

    Step 5: Call BaseApplication class from your AndroidManifest.xml file.

    <application
            android:name=".activity.BaseApplication"
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:supportsRtl="true"
            android:theme="@style/AppTheme"
            .....
    

    Step 6: Create your model which will extend RealmObject class.

    public class Person extends RealmObject{
        private int id;
        private String name;
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    }

    Step 7: Create an instance of Realm in your activity class.

    realm = Realm.getDefaultInstance();

    Step 8: Now you can start your transaction to store, retrieve, update and delete data from Realm.

    package com.testapplication.activity;
    
    import android.os.AsyncTask;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;
    import com.testapplication.R;
    import com.testapplication.model.Person;
    import io.realm.Realm;
    import io.realm.RealmResults;
    
    public class PersonActivity extends AppCompatActivity {
    
        public static final String TAG = "PersonActivity";
        private Realm realm;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_person);
            realm = Realm.getDefaultInstance();
            addPerson(realm);
            getPerson(realm);
            //For complex query do transaction using async task
            new AsyncTask<Void, Void, String>() {
                @Override
                protected String doInBackground(Void... voids) {
                    String info;
                    info = complexReadWriteQuery();
                    info += complexReadQuery();
                    return info;
                }
    
                @Override
                protected void onPostExecute(String result) {
                    Log.i(TAG,"Status: "+result);
                }
            }.execute();
        }
    
        @Override
        protected void onDestroy() {
            super.onDestroy();
            realm.close(); // Close Realm once done.
        }
        private void addPerson(Realm realm){
            // Safe multi threading
            realm.executeTransaction(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {
                    // Add a person
                    Person person = realm.createObject(Person.class);
                    person.setId(1);
                    person.setName("Joe");
                    }
            });
    }
        private void getPerson(Realm realm){
            RealmResults<Person> personList = realm.where(Person.class).findAll();
            Log.i(TAG,"Size: "+personList.size());
            for(Person person:personList){
                Log.i(TAG, "Person Id: "+person.getId());
                Log.i(TAG, "Person Name: "+person.getName());
            }
        }
        private void deleteAll(Realm realm){
            realm.executeTransaction(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {
                    realm.delete(Person.class);
                }
            });
        }
    
        private String complexReadWriteQuery() {
            String status;
            // All threads must use its own reference to the realm. It can not be transferred across threads.
            Realm realm = Realm.getDefaultInstance();
            // Add ten persons in one transaction
            realm.executeTransaction(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {
                    for (int i = 0; i < 10; i++) {
                        Person person = realm.createObject(Person.class);
                        person.setId(i);
                        person.setName("Person name " + i);
    
                    }
                }
            });
            status = "Number of persons: " + realm.where(Person.class).count();
            realm.close();
            return status;
        }
        private String complexReadQuery() {
            String status ="";
    
            Realm realm = Realm.getDefaultInstance();
            status += "Number of persons: " + realm.where(Person.class).count();
    
            // Find all persons where id greater than 7.
            RealmResults<Person> personList = realm.where(Person.class)
                    .greaterThan("id", 7).findAll();
    
            status += "\nSize of result set: " + personList.size();
            for(Person person : personList){
    
                Log.i(TAG, "Complex query Person Id: "+person.getId());
            }
            realm.close();
            return status;
        }
    }
    

    For any query write down your comment below.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: