Home Android Realm : GridView – Write,Read,Show

Android Realm : GridView – Write,Read,Show

Android Realm : GridView – Write,Read,Show


Language :
Platform :
Type :


Android Realm GridView tutorial.

Introduction

In this tutorial we shall see how to first write data into a Realm database from an edittext.We show a Material Dialog with EditText and button.User clicks the save button after typing into the edittext and we save the data into Realm database.

Then when the user clicks retrieve button we read data from Real database and fill an arraylist.This arraylist we shall then bind to our GridView.

Source Code

 

 

 

Android GridView Realm Project Structure

Android GridView Realm Project Structure

 

First we need to add the Realm dependency in our build.gradle :

 

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0'
    compile 'com.android.support:design:23.3.0'
    compile 'io.realm:realm-android:0.82.1'
}

 

Once we have our dependency,we shall create our data object class :

 

package com.tutorials.hp.gridviewrealm.m_Realm;

import io.realm.RealmObject;

/**
 * Created by Oclemy on 6/14/2016 for ProgrammingWizards Channel and http://www.camposha.com.
 */
public class Spacecraft extends RealmObject{

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

 

Thats our Spacecraft model class with two properties.The next thing is we shall craft a simple RealHelper class to assist us in performing our Real CRUD operations.Saving/Writing to Realm,Reading/Retrieving then filling our arraylist.

Here's the RealHelper CRUD class :

 

package com.tutorials.hp.gridviewrealm.m_Realm;

import java.util.ArrayList;

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

/**
 * Created by Oclemy on 6/14/2016 for ProgrammingWizards Channel and http://www.camposha.com.
 */
public class RealmHelper {

    Realm realm;

    public RealmHelper(Realm realm) {
        this.realm = realm;
    }

    //SAVE OR WRITE
    public void save(final Spacecraft spacecraft)
    {
        realm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {

                Spacecraft s=realm.copyToRealm(spacecraft);

            }
        });
    }

    //RETRIEVE OR READ
    public ArrayList<String> retrieve()
    {
        ArrayList<String> spacecraftNames=new ArrayList<>();
        RealmResults<Spacecraft> spacecrafts=realm.where(Spacecraft.class).findAll();

        for(Spacecraft s:spacecrafts)
        {
            spacecraftNames.add(s.getName());
        }

        return spacecraftNames;
    }
}







 

Android Save To Realm

Android Save To Realm

 

 

Finally we shall have our MainActivity class.The class shall display our input dialog to the user whenever he clicks the FloatingActionButton.He types then we pass the typed data into RealHelper class for it to be inserted to Realm database.We shall also bind our data to GridView via an adapter in this class.

 

package com.tutorials.hp.gridviewrealm;

import android.app.Dialog;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.Toast;


import com.tutorials.hp.gridviewrealm.m_Realm.RealmHelper;
import com.tutorials.hp.gridviewrealm.m_Realm.Spacecraft;

import java.util.ArrayList;

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

public class MainActivity extends AppCompatActivity {

    Realm realm;
    ArrayList<String> spacecrafts;
    ArrayAdapter adapter;
    GridView gv;
    EditText nameEditText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);

        gv= (GridView) findViewById(R.id.gv);

        //SETUP REALM
        RealmConfiguration config=new RealmConfiguration.Builder(this).build();
        realm=Realm.getInstance(config);

        //RETRIEVE
        RealmHelper helper=new RealmHelper(realm);
        spacecrafts=helper.retrieve();

        //BIND
        adapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,spacecrafts);
        gv.setAdapter(adapter);

        //ITEMCLICKS
        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(MainActivity.this,spacecrafts.get(position),Toast.LENGTH_SHORT).show();
            }
        });

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                displayInputDialog();
            }
        });
    }

    //DISPLAY INPUT DIALOG
    private void displayInputDialog()
    {
        Dialog d=new Dialog(this);
        d.setTitle("Save to Realm");
        d.setContentView(R.layout.input_dialog);

        nameEditText= (EditText) d.findViewById(R.id.nameEditText);
        Button saveBtn= (Button) d.findViewById(R.id.saveBtn);

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

                //GET DATA AND SAVE
                String name=nameEditText.getText().toString();
                Spacecraft s=new Spacecraft();
                s.setName(name);

                RealmHelper helper=new RealmHelper(realm);
                helper.save(s);
                nameEditText.setText("");

                //RERIEVE OR REFRESH
                spacecrafts=helper.retrieve();
                adapter=new ArrayAdapter(MainActivity.this,android.R.layout.simple_list_item_1,spacecrafts);
                gv.setAdapter(adapter);

            }
        });

        d.show();
    }



}














 

 

Android GridView Realm database

Android GridView Realm database

 

Conclusion

Look,we  have seen how to work with Realm data in our android app.First we've seen how to save data to Realm,then retrieve that data on button click,filling an arraylist.Which of course we bind to our GridView to be displayed.The source code is above for download.Download it,extract and import to your android studio.You can change the Realm version in our dependencies.

If you prefer video tutorial and step by step explanation with demo then watch one here :

Cheers.

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    17 + 19 =

    Leave a Comment

    5 + 20 =