How to migrate Android Room Database if new table is added

In this android programming source code example, we are going to migrate Android Room Database if new table is added.

You can copy and adopt this source code example to your android project without reinventing the wheel.

Below is a step by step source code to migrate Android Room Database if new table is added.

activity_main.xml

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

    <android.support.design.widget.TextInputLayout
        android:id="@+id/nameinput"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <EditText
            android:id="@+id/name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/name"
            android:inputType="textNoSuggestions"
            android:maxLines="1"
            android:singleLine="true" />
    </android.support.design.widget.TextInputLayout>

    <Button
        android:id="@+id/saveBtn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorAccent"
        android:layout_below="@id/nameinput"
        android:textColor="#ffffff"
        android:text="Save"/>

</RelativeLayout>

MainActivity.java

import android.arch.persistence.db.SupportSQLiteDatabase;
import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Database;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.Ignore;
import android.arch.persistence.room.PrimaryKey;
import android.arch.persistence.room.Room;
import android.arch.persistence.room.RoomDatabase;
import android.arch.persistence.room.migration.Migration;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import io.reactivex.Completable;
import io.reactivex.CompletableObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.schedulers.Schedulers;

public class RoomDatabaseActivity7 extends AppCompatActivity {
    private EditText name;
    private Button save;
    private UserDatabase userDatabase;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_room_database7);
        name = (EditText) findViewById(R.id.name);
        save = (Button) findViewById(R.id.saveBtn);
        userDatabase = UserDatabase.getInstance(this);
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String enteredname = name.getText().toString();
                saveUser(enteredname);
            }
        });
    }


    private void saveUser(final String ename){
        Completable.fromAction(new Action() {
            @Override
            public void run() throws Exception {
                User user = new User(ename);
                userDatabase.userDAO().insert(user);
            }
        }).observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new CompletableObserver() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onComplete() {
                        Toast.makeText(RoomDatabaseActivity7.this, "Data store successfully",Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(RoomDatabaseActivity7.this, "Data not store",Toast.LENGTH_LONG).show();
                    }
                });
    }
}

UserDatabase.java

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.arch.persistence.room.migration.Migration;
import android.content.Context;
import android.support.annotation.NonNull;

import java.util.concurrent.Executors;

@Database(entities = { User.class }, version = 2, exportSchema = false)
public abstract class UserDatabase extends RoomDatabase {
    private static final String DB_NAME ="UserDb";
    private static UserDatabase instance;
    public abstract UserDAO userDAO();
    private static final Migration MIGRATION_1_2 =new Migration(1, 2) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            database.execSQL("CREATE TABLE IF NOT EXISTS 'users' ('id' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 'name' TEXT NOT NULL)");
        }
    };


    public synchronized static UserDatabase getInstance(final Context context) {
        if (instance == null) {
            instance = Room.databaseBuilder(context, UserDatabase.class, DB_NAME)
                    .addMigrations(MIGRATION_1_2)
                    .allowMainThreadQueries().build();
        }
        return instance;
    }
}

UserDAO.java

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.ArrayList;
import java.util.List;

@Dao
public interface UserDAO {
    @Query("select * from users")
    List<User> getuserList();

    @Insert
    public void insert(User user);

    @Update
    public void update(User user);

    @Delete
    public void delete(User user);

}

User.java

import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.Ignore;
import android.arch.persistence.room.PrimaryKey;

@Entity(tableName = "users")
public class User {
    @PrimaryKey(autoGenerate = true)
    private int id;
    @ColumnInfo(name = "name")
    private String name;
    public User(int id, String name){
        this.id = id;
        this.name = name;
    }
    @Ignore
    public User(String name){
        this.name = name;
    }
    public int getId() {
        return id;
    }
    public String getName() {
        return name;
    }
}

build.gradle

implementation 'io.reactivex.rxjava2:rxjava:2.1.9'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
implementation 'android.arch.persistence.room:runtime:1.0.0' 
annotationProcessor 'android.arch.persistence.room:compiler:1.0.0'

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

 

Add a Comment