Android Realm Database Spinner Tutorial


Android Realm Spinner Tutorials and Examples.*

How to perform basic CRUD in Realm with Spinner as our widget.

Android Realm CRUD - Spinner - Save,Retrieve,Show

Hello this is a simple realm tutorial to perform basic CRUD.We  first write data to Realm database from a simple dialog with edittext,then read that data and show in a simple spinner. Here's the thing :

  • Save/Write data to realm database from a simple edittext on button click.
  • Our EditText and Button are hosted in a dialog that gets shown on floating action button is clicked.
  • Retrieve.Read data From Realm database filling  a simple arraylist.
  • Bind the arraylist in a simple spinner.

Realm is a fast mobile database that allows us to write database code in pure Java.

This gives us type safety and provides for greater flexibility than writing SQL code.

Type safety allows us easily catch errors at compile time.

This is a realm database tutorial with spinner.

Spinner is an android adapterview that allows us display items in a dropdown manner.

In this tutorial we save data to Realm database, retrieve data and show in a Spinner.

Let's go.

Spinner Realm

Spinner Realm

Spinner Realm

1. Create Basic Activity Project

  1. First create an empty project in android studio. Go to File --> New Project.

3. Create User Interface

User interfaces are typically created in android using XML layouts as opposed by direct java coding.

This is an example fo declarative programming.

Here are our layouts for this project:

(a). activity_main.xml
  • This layout gets inflated to MainActivity user interface.
  • It includes the content_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:fitsSystemWindows="true"
    tools:context="com.tutorials.hp.spinnerrealm.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        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.design.widget.AppBarLayout>

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

    <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_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>
(b). content_main.xml

This layout gets included in your activity_main.xml. The adapterview we use is a spinner so add spinner in your layout.

<?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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.tutorials.hp.spinnerrealm.MainActivity"
    tools:showIn="@layout/activity_main">

    <Spinner
        android:id="@+id/sp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
         />
</RelativeLayout>
(c). input_dialog.xml

This is our input dialog.

This dialog will be shown as our entry form.

Users will enter save data to realm database via this dialog.

It basically comprises edittext and button.

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

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="?attr/actionBarSize"
        android:orientation="vertical"
        android:paddingLeft="15dp"
        android:paddingRight="15dp"
        android:paddingTop="50dp">

        <android.support.design.widget.TextInputLayout
            android:id="@+id/nameLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <EditText
                android:id="@+id/nameEditText"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:singleLine="true"
                android:hint= "Name" />
        </android.support.design.widget.TextInputLayout>

        <Button android:id="@+id/saveBtn"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Save"
            android:clickable="true"
            android:background="@color/colorAccent"
            android:layout_marginTop="40dp"
            android:textColor="@android:color/white"/>

    </LinearLayout>
</LinearLayout>

Java Classes

Let's now come to our Java classes.

Our Realm classes

Here are our Realm database classes.

(a). Spacecraft.java

This class is both our model class as well as our Realm model class.

This means that Realm will create a table for this class.

For that to happen we have to derive from RealmObject class.

package com.tutorials.hp.spinnerrealm.m_Realm;

import io.realm.RealmObject;

public class Spacecraft extends RealmObject {

    private String name;

    public String getName() {
        return name;
    }

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

This is like our CRUD class.

It's here that we actually save data to realm database and retrieve data as well.

package com.tutorials.hp.spinnerrealm.m_Realm;

import java.util.ArrayList;

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

public class RealmHelper {

    Realm realm;

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

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

                Spacecraft s=realm.copyToRealm(spacecraft);

            }
        });
    }

    //READ/RETRIEVE
    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;
    }
}
Our Activity class
(a). MainActivity.java

This is our Activity class.

Activity is an android component representing User interface.

Our activity will host a spinner and a dialog that acts as our input form.

package com.tutorials.hp.spinnerrealm;

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.Spinner;
import android.widget.Toast;

import com.tutorials.hp.spinnerrealm.m_Realm.RealmHelper;
import com.tutorials.hp.spinnerrealm.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;
    Spinner sp;
    EditText nameEdiText;

    @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);

        sp= (Spinner) findViewById(R.id.sp);

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

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

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

        //ONCLICK
        sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(MainActivity.this,spacecrafts.get(position),Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

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

    private void displayInputDialog()

    {
        Dialog d=new Dialog(this);
        d.setTitle("save To Realm");
        d.setContentView(R.layout.input_dialog);

        nameEdiText= (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) {

                Spacecraft s=new Spacecraft();
                s.setName(nameEdiText.getText().toString());

                //save
                RealmHelper helper=new RealmHelper(realm);
                helper.save(s);

                nameEdiText.setText("");
                //RETRIEVE
                spacecrafts=helper.retrieve();
                adapter=new ArrayAdapter(MainActivity.this,android.R.layout.simple_list_item_1,spacecrafts);

                sp.setAdapter(adapter);

            }
        });

        d.show();

    }

}

Download

No. Location Link
1. GitHub Direct Download)
2. GitHub Browse
3. YouTube Video Tutorial
4. YouTube Our YouTube Channel

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post