Update and delete items from Room database

I already made a tutorial how to read/write from Room persistence, library here is the link:

Add data to SQLite Room, fetch it and display it into RecyclerView


so, I decided to make tutorial how to update and delete elements.



Lets say your entity class Item looks like this:

Item.java
 package com.notifications.youtube.azem.virtuoozatutorials;

import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;
import android.support.annotation.NonNull;

/**
 * Created by azem on 12/30/17.
 */

@Entity
public class Item {

    @PrimaryKey
    @NonNull
    private String id;

    @ColumnInfo(name = "name")
    private String name;



    public Item() {
    }

    public Item(@NonNull String id, String name) {
        this.id = id;
        this.name = name;
    }

    @NonNull
    public String getId() {
        return id;
    }

    public void setId(@NonNull String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

In my interface, I will add methods for adding, deleting and updating the elements:

LocalDatabaseInterface.java
package com.notifications.youtube.azem.virtuoozatutorials;

import java.util.List;

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;
/**
 * Created by azem on 12/30/17.
 */

@Dao
public interface LocalDatabaseInterface {

    @Query("SELECT * FROM item")
    List<Item> getItems();

    @Insert
    void insertAll(Item... items);

    @Delete
    public void deleteUsers(Item... items);

    @Update
    public void updateUsers(Item... items);
}

This is my contract class for my database:

AppDatabase.java
package com.notifications.youtube.azem.virtuoozatutorials;

import android.arch.persistence.db.SupportSQLiteOpenHelper;
import android.arch.persistence.room.Database;
import android.arch.persistence.room.DatabaseConfiguration;
import android.arch.persistence.room.InvalidationTracker;
import android.arch.persistence.room.RoomDatabase;

/**
 * Created by azem on 12/30/17.
 */

@Database(entities = {Item.class},version = 1)
public abstract class AppDatabase extends RoomDatabase {

    public abstract LocalDatabaseInterface databaseInterface();

    @Override
    protected SupportSQLiteOpenHelper createOpenHelper(DatabaseConfiguration config) {
        return null;
    }

    @Override
    protected InvalidationTracker createInvalidationTracker() {
        return null;
    }
}

This is my activity_main.xml

activity_main.xml
<?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"
    tools:context="com.notifications.youtube.azem.virtuoozatutorials.MainActivity">

    <TextView
        android:id="@+id/item"
        android:layout_alignParentTop="true"
        android:layout_margin="20dp"
        android:textSize="20sp"
        android:textColor="#000"
        android:text="No item for now"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:layout_marginTop="100dp"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <Button
            android:id="@+id/insert"
            android:text="insert"
            android:layout_margin="10dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/update"
            android:text="update"
            android:layout_margin="10dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/delete"
            android:text="delete"
            android:layout_margin="10dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </LinearLayout>

</RelativeLayout>

This is my MainActivity class in which I will add an element to the database, update it and delete it:

MainActivity.java
package com.notifications.youtube.azem.virtuoozatutorials;

import android.arch.persistence.room.Room;
import android.database.sqlite.SQLiteConstraintException;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends AppCompatActivity {

    AppDatabase db;
    Button insert, update, delete;
     Item item;
     TextView itemTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        db = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, "production")
                .build();

        insert=(Button)findViewById(R.id.insert);
        update=(Button)findViewById(R.id.update);
        delete=(Button)findViewById(R.id.delete);
        itemTextView=(TextView)findViewById(R.id.item);
        
        //here I am instatiating an item which I will later add to database
        item = new Item("originalId","itemName");

        insert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AsyncTask.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            // here I am inserting the item into database
                            db.databaseInterface().insertAll(item);
                            runOnUiThread(new Runnable() {
                                public void run() {
                                    // here I am displaying it
                                    itemTextView.setText(item.getName());
                                      }
                            });
                        }
                        catch (SQLiteConstraintException ex){
                            runOnUiThread(new Runnable() {
                                public void run() {
                                    Toast.makeText(getApplicationContext(),"Item already added",Toast.LENGTH_LONG).show();
                                }
                            });
                        }
                    }
                });
            }
        });

        update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) { 
                // here I am changing current name of our item, but ID must remain same if we want to update element in database
                item.setName("newName")
                AsyncTask.execute(new Runnable() {
                    @Override
                    public void run() {
                        AsyncTask.execute(new Runnable() {
                            @Override
                            public void run() {
                                // and now I am updating the element in databaseRoom
                                db.databaseInterface().updateUsers(item);
                                runOnUiThread(new Runnable() {
                                    public void run() {
                                        itemTextView.setText(item.getName());
                                    }
                                });
                            }
                        });
                    }
                });
            }
        });

        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AsyncTask.execute(new Runnable() {
                    @Override
                    public void run() {
                        AsyncTask.execute(new Runnable() {
                            @Override
                            public void run() {
                                 // and deleting
                                db.databaseInterface().deleteUsers(item);
                                runOnUiThread(new Runnable() {
                                    public void run() {
                                        itemTextView.setText("item deleted");
                                    }
                                });
                            }
                        });
                    }
                });
            }
        });
        
    }
}



And that’s it. This is how you perform updating and deleting in Room.
For a bit more detailed explanations on Room database, please check out my previous tutorial:

Add data to SQLite Room, fetch it and display it into RecyclerView

Share with your friends
Tagged with: