ROOM ローカルデータベース

Googleのドキュメント

https://developer.android.com/training/data-storage/room?hl=ja

AndroidのSQLiteのラッパーでDAOからデータアクセスできるので便利。

アプリのgradleに追加

dependencies {
  def room_version = "2.2.5"

  implementation "androidx.room:room-runtime:$room_version"
  annotationProcessor "androidx.room:room-compiler:$room_version"

  // optional - RxJava support for Room
  implementation "androidx.room:room-rxjava2:$room_version"

  // optional - Guava support for Room, including Optional and ListenableFuture
  implementation "androidx.room:room-guava:$room_version"

  // optional - Test helpers
  testImplementation "androidx.room:room-testing:$room_version"
}

MainActivity.java

package jp.mknod.app.roomtest;

import androidx.appcompat.app.AppCompatActivity;
import androidx.room.Room;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import java.util.List;

public class MainActivity extends AppCompatActivity {

	AppDatabase db;
	UserDao dao;
	EditText edit_last;
	EditText edit_first;
	Button bt_insert;
	Button bt_select;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);


		db = Room.databaseBuilder(getApplicationContext(),
			AppDatabase.class, "database-name").build();
		dao = db.userDao();

		bt_insert = findViewById(R.id.bt_insert);
		bt_select = findViewById(R.id.bt_select);
		edit_first = findViewById(R.id.edit_first);
		edit_last = findViewById(R.id.edit_last);

		bt_insert.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {

				new Thread(new Runnable() {
					@Override
					public void run() {
						User u = new User();
						u.firstName = edit_first.getText().toString();
						u.lastName = edit_last.getText().toString();
						dao.insertAll(u);
					}
				}).start();
			}
		});

		bt_select.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {

				new Thread(new Runnable() {
					@Override
					public void run() {

						List<User> list;
						list = dao.getAll();
						Log.d("ROOM_TEST", "Size=" + Integer.valueOf(list.size()) );

						for(int i=0; i< list.size(); i++) {
							Log.d("AAA", list.get(i).firstName );
						}
					}
				}).start();

			}
		});
	}
}

AppDatabese.java

package jp.mknod.app.roomtest;

import androidx.room.Database;
import androidx.room.RoomDatabase;

@Database(entities = {User.class}, version = 1, exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {
	public abstract UserDao userDao();
}

User.java

package jp.mknod.app.roomtest;

import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;

@Entity
public class User {
	@PrimaryKey(autoGenerate = true)
	public int uid;

	@ColumnInfo(name = "first_name")
	public String firstName;

	@ColumnInfo(name = "last_name")
	public String lastName;
}

UserDao.java

package jp.mknod.app.roomtest;

import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;

import java.util.List;

@Dao
public interface UserDao {
	@Query("SELECT * FROM user")
	List<User> getAll();

	@Query("SELECT * FROM user WHERE uid IN (:userIds)")
	List<User> loadAllByIds(int[] userIds);

	@Query("SELECT * FROM user WHERE first_name LIKE :first AND " +
		"last_name LIKE :last LIMIT 1")
	User findByName(String first, String last);

	@Insert
	void insertAll(User... users);

	@Delete
	void delete(User user);
}