How to perform Select and Insert in Room database android?

Room is a new SQLITE abstraction layer added by google. It is very interesting as well as tough to understand initially.

Where to start?

The very first thing we need to do is we need to create model class. The model class holds our data which we want to insert into room database.We can use Set and get methods to add our data and Get about data from model and then update our database.

What you can do with this code?

  • INSERT
  • SELECT
  • UPDATE
  • DELETE

Model to insert

package com.android.boom;

public class myModel {

    String myString;
    Boolean myBoolean;
    int myNumber;
    long myLongNumber;
    double myDouble;

    public myModel() {
    }

    public String getMyString() {
        return myString;
    }

    public void setMyString(String myString) {
        this.myString = myString;
    }

    public Boolean getMyBoolean() {
        return myBoolean;
    }

    public void setMyBoolean(Boolean myBoolean) {
        this.myBoolean = myBoolean;
    }

    public int getMyNumber() {
        return myNumber;
    }

    public void setMyNumber(int myNumber) {
        this.myNumber = myNumber;
    }

    public long getMyLongNumber() {
        return myLongNumber;
    }

    public void setMyLongNumber(long myLongNumber) {
        this.myLongNumber = myLongNumber;
    }

    public double getMyDouble() {
        return myDouble;
    }

    public void setMyDouble(double myDouble) {
        this.myDouble = myDouble;
    }
}

Add Dependency in Project

  implementation 'android.arch.persistence.room:runtime:1.1.1'
  annotationProcessor 'android.arch.persistence.room:compiler:1.1.1'

Create AppDatabase Class

package com.android.boom_room_1;




import android.arch.persistence.db.SupportSQLiteDatabase;
import android.arch.persistence.room.Database;
import android.arch.persistence.room.Room;
import android.arch.persistence.room.RoomDatabase;
import android.content.Context;
import android.support.annotation.NonNull;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.concurrent.Executors;

@Database(entities = {MyModel.class}, version = 1, exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {
    private static AppDatabase INSTANCE;
    public abstract MyDao myDao();


    public synchronized static AppDatabase getInstance(Context context) {
        if (INSTANCE == null) {
            INSTANCE = buildDatabase(context);
        }
        return INSTANCE;
    }

    private static AppDatabase buildDatabase(final Context context) {
        return Room.databaseBuilder(context,
                AppDatabase.class,
                "myDB")
                .build();
    }


}

Create DAO (Data Access Object) Class

package com.android.boom_room_1;

import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Delete;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.Query;
import android.arch.persistence.room.Update;

import java.util.List;

@Dao
public interface MyDao {
    @Query("SELECT * FROM mymodel")
    List<MyModel> getAll();

    @Insert
    void insert(MyModel myModel);

    @Delete
    void delete(MyModel myModel);

    @Update
    void update(MyModel myModel);
}

These are

activity_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"
    tools:context=".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"
        app:srcCompat="@android:drawable/ic_dialog_email" />

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

Create XML Layout to Insert Values

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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:id="@+id/relativeLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".MainActivity"
    tools:showIn="@layout/activity_main">

    <EditText
        android:id="@+id/myString"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="93dp"
        android:layout_marginTop="51dp"
        android:layout_marginEnd="104dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="My String"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:layout_conversion_wrapHeight="118"
        tools:layout_conversion_wrapWidth="560" />

    <EditText
        android:id="@+id/myInt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="1dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="9"
        app:layout_constraintEnd_toEndOf="@+id/myString"
        app:layout_constraintStart_toStartOf="@+id/myString"
        app:layout_constraintTop_toBottomOf="@+id/myString"
        tools:layout_conversion_wrapHeight="118"
        tools:layout_conversion_wrapWidth="560" />

    <EditText
        android:id="@+id/myBoolean"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="false"
        app:layout_constraintEnd_toEndOf="@+id/myInt"
        app:layout_constraintStart_toStartOf="@+id/myInt"
        app:layout_constraintTop_toBottomOf="@+id/myInt" />

    <EditText
        android:id="@+id/myDouble"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="0.32222"
        app:layout_constraintEnd_toEndOf="@+id/myBoolean"
        app:layout_constraintStart_toStartOf="@+id/myBoolean"
        app:layout_constraintTop_toBottomOf="@+id/myBoolean" />
</android.support.constraint.ConstraintLayout>

Create Activity and Java Code to run our logic

We will grab the values from our text fields and will insert in to Room Database.

Insert Data

All will be handled in Async Task because these operations should run on other thread and not on main thread.

    private void insertMyData() {


        // Get data from all text views
        final EditText myBoolean = findViewById(R.id.myBoolean);
        final EditText myString = findViewById(R.id.myString);
        final EditText myInteger = findViewById(R.id.myInt);
        final EditText myDouble = findViewById(R.id.myDouble);

        final boolean myBoolValue = Boolean.valueOf(myBoolean.getText().toString());
        final double myDoubleValue = Double.parseDouble(myDouble.getText().toString());
        final int myIntegerValue = Integer.parseInt(myInteger.getText().toString());
        // add them in model

        //then add model to table via asynctask


        class UpdateTask extends AsyncTask<Void, Void, Void> {

            @Override
            protected Void doInBackground(Void... voids) {
                MyModel myModel = new MyModel();
                myModel.setMyBoolean(myBoolValue);
                myModel.setMyDouble(myDoubleValue);
                myModel.setMyInteger(myIntegerValue);
                myModel.setMyString("MY DUMMY STRING");


                AppDatabase.getInstance(getApplicationContext())
                        .myDao()
                        .insert(myModel);
                return null;

            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);

                ShowMyData();
            }
        }

        UpdateTask ut = new UpdateTask();
        ut.execute();
    }

Show my data

   private void ShowMyData() {

        class GetMyDataTask extends AsyncTask<Void, Void, List<MyModel>> {

            @Override
            protected List<MyModel> doInBackground(Void... voids) {
                List<MyModel> list = AppDatabase.getInstance(getApplicationContext()).myDao().getAll();

                return list;

            }

            @Override
            protected void onPostExecute(List<MyModel> list) {
                super.onPostExecute(list);
                String myResult="";
                TextView result = findViewById(R.id.result);
                for (int i = 0; i <list.size() ; i++) {
                   myResult += "MyString:"+list.get(i).getMyString()+"\n"
                                +"MyDouble"+list.get(i).getMyDouble()+"\n"
                                +"MyID"+list.get(i).getId()+"\n"
                                +"MyBoolean"+list.get(i).getMyBoolean()+"\n"
                                +"MyInteger"+list.get(i).getMyInteger()+"\n\n";
                }
                result.setText(myResult);
            }
        }

        GetMyDataTask ut = new GetMyDataTask();
        ut.execute();
    }

MainActivity

package com.android.boom_room_1;

import android.os.AsyncTask;
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.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Text;

import java.util.List;
import java.util.Random;

public class MainActivity extends AppCompatActivity {

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

        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                insertMyData();

                Snackbar.make(view, "Inserted", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }

    private void insertMyData() {


        // Get data from all text views
        final EditText myBoolean = findViewById(R.id.myBoolean);
        final EditText myString = findViewById(R.id.myString);
        final EditText myInteger = findViewById(R.id.myInt);
        final EditText myDouble = findViewById(R.id.myDouble);

        final boolean myBoolValue = Boolean.valueOf(myBoolean.getText().toString());
        final double myDoubleValue = Double.parseDouble(myDouble.getText().toString());
        final int myIntegerValue = Integer.parseInt(myInteger.getText().toString());
        // add them in model

        //then add model to table via asynctask


        class UpdateTask extends AsyncTask<Void, Void, Void> {

            @Override
            protected Void doInBackground(Void... voids) {
                MyModel myModel = new MyModel();
                myModel.setMyBoolean(myBoolValue);
                myModel.setMyDouble(myDoubleValue);
                myModel.setMyInteger(myIntegerValue);
                myModel.setMyString("MY DUMMY STRING");


                AppDatabase.getInstance(getApplicationContext())
                        .myDao()
                        .insert(myModel);
                return null;

            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);

                ShowMyData();
            }
        }

        UpdateTask ut = new UpdateTask();
        ut.execute();
    }

    private void ShowMyData() {

        class GetMyDataTask extends AsyncTask<Void, Void, List<MyModel>> {

            @Override
            protected List<MyModel> doInBackground(Void... voids) {
                List<MyModel> list = AppDatabase.getInstance(getApplicationContext()).myDao().getAll();

                return list;

            }

            @Override
            protected void onPostExecute(List<MyModel> list) {
                super.onPostExecute(list);
                String myResult="";
                TextView result = findViewById(R.id.result);
                for (int i = 0; i <list.size() ; i++) {
                   myResult += "MyString:"+list.get(i).getMyString()+"\n"
                                +"MyDouble"+list.get(i).getMyDouble()+"\n"
                                +"MyID"+list.get(i).getId()+"\n"
                                +"MyBoolean"+list.get(i).getMyBoolean()+"\n"
                                +"MyInteger"+list.get(i).getMyInteger()+"\n\n";
                }
                result.setText(myResult);
            }
        }

        GetMyDataTask ut = new GetMyDataTask();
        ut.execute();
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

TIPS:

  • Room Database Save Boolean values as 0 or 1 as true and false are not supported in SQLite database.
  • Room database can be added with Live data so you can see updates instantly while using Listview, RecyclerView etc

Conclusion

I am an ordinary man.. 🙂
I may write ordinary code but it may help you to get started with it.
Good Luck..
from Android Boom,
Android Blog Of Ordinary Man