Tuesday, 27 October 2020

ROOM DATABASE TUTORIAL

Download Full Source Code


1. Create New Android App


2. Update Gradle Files

ext {
roomVersion = '2.2.1'
}


3.Add the following code to the end of the dependencies block:

// Room components
implementation "androidx.room:room-runtime:$rootProject.roomVersion"
annotationProcessor "androidx.room:room-compiler:$rootProject.roomVersion"
androidTestImplementation "androidx.room:room-testing:$rootProject.roomVersion"



4. Create Class Student.class

@Entity
public class Student
{

    @PrimaryKey(autoGenerate = true)
    int ID;
    @NonNull
    @ColumnInfo(name = "name")
    private String name;

    public Student(String name)
    {
        this.name = name;
    }

    public String getName()
    {
        return this.name;
    }


}


5. Create Dao Interface


@Dao
public interface StudentDao {

    // allowing the insert of the same word multiple times by passing a
    // conflict resolution strategy
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void insert(Student student);

    @Query("DELETE FROM student")
    void deleteAll();

    @Query("SELECT * from student ORDER BY ID ASC")
    List<Student> getAll();
}


6. Create Database Class :


@Database(entities = {Student.class}, version = 3, exportSchema = false)
public abstract class StudentRoomDatabase extends RoomDatabase
{

    public abstract StudentDao studentDao();

    private static volatile StudentRoomDatabase INSTANCE;
    private static final int NUMBER_OF_THREADS = 4;
    static final ExecutorService databaseWriteExecutor =
            Executors.newFixedThreadPool(NUMBER_OF_THREADS);

    static StudentRoomDatabase getDatabase(final Context context)
    {
        if (INSTANCE == null)
        {
            synchronized (StudentRoomDatabase.class)
            {
                if (INSTANCE == null)
                {
                    INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                            StudentRoomDatabase.class, "db")
                            .allowMainThreadQueries()
                            .build();
                }
            }
        }
        return INSTANCE;
    }
}


7. Create MainActivity.java 

public class MainActivity extends AppCompatActivity
{
    EditText et;
    Button btnInsert;
    ListView listView;
    StudentRoomDatabase db;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et = findViewById(R.id.etName);
        btnInsert = findViewById(R.id.btnInsert);
        listView = findViewById(R.id.listView);

        db = StudentRoomDatabase.getDatabase(getApplicationContext());
        loadListView();

        btnInsert.setOnClickListener(view ->
        {
            String name = et.getText().toString().trim();
            if (TextUtils.isEmpty(name))
            {
                Toast.makeText(this, "Invalid inputs", Toast.LENGTH_SHORT).show();
                return;
            }


            Student std = new Student(et.getText().toString().trim());
            db.studentDao().insert(std);
            et.setText("");
            loadListView();
        });
    }

    private void loadListView()
    {
        ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, db.studentDao().getAll());
        listView.setAdapter(adapter);
    }
}



8. Create Layout File activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">


    <EditText
        android:layout_width="match_parent"
        android:id="@+id/etName"
        android:hint="Enter Name"
        android:layout_height="wrap_content"></EditText>
    <Button
        android:layout_width="wrap_content"
        android:text="Insert"
        android:id="@+id/btnInsert"
        android:onClick="insert"
        android:layout_height="wrap_content"></Button>
    <ListView
        android:layout_width="match_parent"
        android:id="@+id/listView"
        android:layout_height="wrap_content"></ListView>
</LinearLayout>



No comments:

Post a Comment