1. Beschreibung
Room ist Teil von Android Jetpack, das eine auf SQLite basierende Abstraktionsschicht bereitstellt. Dieser Artikel implementiert eine Demo mit Room in Kombination mit LiveData und ViewModel.
Zweitens Beispiele
1. Abhängigkeiten hinzufügen
build.gradle (Modul: app) Abhängigkeiten hinzufügen
// Room components
dependencies {
// Room components
implementation "androidx.room:room-runtime:$rootProject.roomVersion"
annotationProcessor "androidx.room:room-compiler:$rootProject.roomVersion"
androidTestImplementation "androidx.room:room-testing:$rootProject.roomVersion"
// Lifecycle components
implementation "androidx.lifecycle:lifecycle-extensions:$rootProject.archLifecycleVersion"
annotationProcessor "androidx.lifecycle:lifecycle-compiler:$rootProject.archLifecycleVersion"
// UI
implementation "com.google.android.material:material:$rootProject.materialVersion"
}
build.gradle (Projekt: room_java) Geben Sie die Versionsnummer ein. Die Versionsnummer kann hier abgerufen werden
ext {
roomVersion = '2.2.5'
archLifecycleVersion = '2.2.0'
materialVersion = '1.0.0'
}
2. Entitätsklasse
@Entity(tableName = "feizai_table")
public class Feizai {
@PrimaryKey
@NonNull
@ColumnInfo(name = "first_name")
private String firstName;
@ColumnInfo(name = "second_name")
private String secondName;
@NonNull
public String getFirstName() {
return firstName;
}
public void setFirstName(@NonNull String firstName) {
this.firstName = firstName;
}
public String getSecondName() {
return secondName;
}
public void setSecondName(String secondName) {
this.secondName = secondName;
}
}
3. Dao-Schnittstelle
Beachten Sie, dass das Datenbank-DAO eine Schnittstelle ist . Beim Löschen und Ändern wird eine Feizai-Klasse übergeben, diese wird jedoch gemäß dem Primärschlüssel der entsprechenden Datenbank in der Feizai-Klasse geändert und gelöscht, dh es spielt keine Rolle, welche anderen Felder in der Feizai-Klasse vorhanden sind Es bearbeitet die Datenbank entsprechend dem Wert des entsprechenden Felds des Primärschlüssels. Der Zweck der Verwendung von LiveData besteht darin, die Datenbank zu überwachen und die Schnittstelle in Echtzeit zu aktualisieren.
@Dao
public interface FeizaiDao {
@Insert(onConflict = OnConflictStrategy.IGNORE)
void insert(Feizai feizai);
@Query("SELECT * FROM feizai_table")
LiveData<List<Feizai>> getAllFeizai();
@Delete(entity = Feizai.class)
void delete(Feizai feizai);
@Update(entity = Feizai.class)
void update(Feizai feizai);
}
4. Datenbankklasse
Wenn Sie die Datenbank ändern, müssen Sie die Version der Datenbank (Version + 1) aktualisieren und Datenbankoperationen in addMigrations hinzufügen. Wenn Sie die Felder in der Datenbanktabelle reduzieren möchten, können Sie eine temporäre Tabelle erstellen, dann die Daten in die temporäre Tabelle migrieren, die alte Datenbanktabelle löschen, dann eine Datenbanktabelle mit demselben Namen wie die alte Datenbank erstellen und dann Migrieren Sie die Daten in der temporären Tabelle in die neue Datenbank. Löschen Sie in der Tabelle die temporäre Datenbanktabelle, um die Felder in der Datenbank zu löschen und die alten Daten zu speichern.
@Database(entities = {
Feizai.class}, version = 1, exportSchema = false)
public abstract class FeizaiDatabase extends RoomDatabase {
public abstract FeizaiDao getFeizaiDao();
private static volatile FeizaiDatabase INSTANCE;
private static final int NUMBER_OF_THREADS = 4;
public static final ExecutorService databaseWriteExecutor =
Executors.newFixedThreadPool(NUMBER_OF_THREADS);
public static FeizaiDatabase getDatabase(Context context) {
if (INSTANCE == null) {
synchronized (FeizaiDatabase.class) {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
FeizaiDatabase.class, "Feizai.db")
.addMigrations(MIGRATION_1_2)
.build();
}
}
}
return INSTANCE;
}
static final Migration MIGRATION_1_2 = new Migration(1, 2) {
@Override
public void migrate(@NonNull SupportSQLiteDatabase database) {
database.execSQL("ALTER TABLE feizai_table ADD COLUMN sex STRING");
}
};
}
5. Repository-Klasse
public class FeizaiRepository {
private FeizaiDao mFeizaiDao;
private LiveData<List<Feizai>> mFeizais;
public FeizaiRepository(Application application) {
FeizaiDatabase db = FeizaiDatabase.getDatabase(application);
mFeizaiDao = db.getFeizaiDao();
mFeizais = mFeizaiDao.getAllFeizai();
}
public LiveData<List<Feizai>> getAllFeizais() {
return mFeizais;
}
public void insert(Feizai feizai) {
FeizaiDatabase.databaseWriteExecutor.execute(new Runnable() {
@Override
public void run() {
mFeizaiDao.insert(feizai);
mFeizais = mFeizaiDao.getAllFeizai();
}
});
}
public void delete(Feizai feizai) {
WordRoomDatabase.databaseWriteExecutor.execute(new Runnable() {
@Override
public void run() {
mFeizaiDao.delete(feizai);
}
});
}
public void update(Feizai feizai) {
WordRoomDatabase.databaseWriteExecutor.execute(new Runnable() {
@Override
public void run() {
mFeizaiDao.update(feizai);
}
});
}
}
6. ViewModel-Klasse
public class FeizaiViewModel extends AndroidViewModel {
private FeizaiRepository mReposity;
private LiveData<List<Feizai>> mAllFeizais;
public FeizaiViewModel (Application application) {
super(application);
mReposity = new FeizaiRepository(application);
mAllFeizais = mReposity.getAllFeizais();
}
public LiveData<List<Feizai>> getmAllFeizais() {
return mAllFeizais;
}
public void insert(Feizai feizai) {
mReposity.insert(feizai);
}
public void delete(Feizai feizai) {
mReposity.delete(feizai);
}
public void update(Feizai feizai) {
mReposity.update(feizai);
}
}
7. Dokument feizai_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_margin="4dp"
style="@style/word_title">
<TextView
android:id="@+id/item_first"
android:layout_marginVertical="10dp"
android:layout_width ="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/item_second"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
8. Aktivität_feizai.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FeizaiActivity">
<EditText
android:id="@+id/first_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:hint="First Name"/>
<EditText
android:id="@+id/second_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@id/first_name"
android:hint="Second Name"/>
<Button
android:id="@+id/btn_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@id/second_name"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toLeftOf="@id/delete"
android:text="@string/insert"/>
<Button
android:id="@+id/delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@id/second_name"
app:layout_constraintLeft_toRightOf="@id/btn_add"
app:layout_constraintRight_toRightOf="parent"
android:text="@string/delete"/>
<Button
android:id="@+id/btn_update"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@id/btn_add"
app:layout_constraintLeft_toLeftOf="@id/btn_add"
android:text="@string/update"/>
<Button
android:id="@+id/insert"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@+id/delete"
app:layout_constraintLeft_toLeftOf="@id/delete"
android:text="占坑"/>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rc_feizai"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_margin="6dp"
app:layout_constraintTop_toBottomOf="@id/btn_update"
app:layout_constraintBottom_toBottomOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
9. FeizaiListAdapter类
public class FeizaiListAdapter extends RecyclerView.Adapter<FeizaiListAdapter.FeizaiViewHolder> {
private final LayoutInflater mInflater;
private List<Feizai> mFeizais;
public FeizaiListAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
@NonNull
@Override
public FeizaiViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView = mInflater.inflate(R.layout.feizai_item, parent, false);
return new FeizaiViewHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull FeizaiViewHolder holder, int position) {
if (mFeizais != null) {
Feizai current = mFeizais.get(position);
holder.itemFirst.setText(current.getFirstName());
holder.itemSecond.setText(current.getSecondName());
} else {
holder.itemFirst.setText("没有查到肥仔");
holder.itemSecond.setText("没有查到肥仔");
}
}
@Override
public int getItemCount() {
if (mFeizais == null)
return 0;
return mFeizais.size();
}
public void setFeizai(List<Feizai> feizais) {
mFeizais = feizais;
notifyDataSetChanged();
}
class FeizaiViewHolder extends RecyclerView.ViewHolder {
private final TextView itemFirst;
private final TextView itemSecond;
private FeizaiViewHolder(View itemView) {
super(itemView);
itemFirst = itemView.findViewById(R.id.item_first);
itemSecond = itemView.findViewById(R.id.item_second);
}
}
}
10. Feizai-Aktivitäten
public class FeizaiActivity extends AppCompatActivity {
private FeizaiViewModel mFeizaiViewModel;
private FeizaiListAdapter adapter;
RecyclerView rv;
EditText firstName, secondName;
Button add, delete, insert, update;
Feizai feizai;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feizai);
initView();
feizai = new Feizai();
mFeizaiViewModel = new ViewModelProvider(this).get(FeizaiViewModel.class);
mFeizaiViewModel.getmAllFeizais().observe(this, feizais -> adapter.setFeizai(feizais));
}
private void initView() {
add = findViewById(R.id.btn_add);
insert = findViewById(R.id.insert);
delete = findViewById(R.id.delete);
update = findViewById(R.id.btn_update);
rv = findViewById(R.id.rc_feizai);
firstName = findViewById(R.id.first_name);
secondName = findViewById(R.id.second_name);
adapter = new FeizaiListAdapter(this);
rv.setAdapter(adapter);
rv.setLayoutManager(new LinearLayoutManager(this));
add.setOnClickListener(v -> {
if (TextUtils.isEmpty(firstName.getText().toString()) && TextUtils.isEmpty(secondName.getText().toString())) {
return;
}
feizai.setFirstName(firstName.getText().toString());
feizai.setSecondName(secondName.getText().toString());
mFeizaiViewModel.insert(feizai);
});
delete.setOnClickListener(v -> {
if (TextUtils.isEmpty(firstName.getText().toString())) {
return;
}
feizai.setFirstName(firstName.getText().toString());
feizai.setSecondName(secondName.getText().toString());
mFeizaiViewModel.delete(feizai);
});
update.setOnClickListener(v -> {
if (TextUtils.isEmpty(firstName.getText().toString())) {
return;
}
feizai.setFirstName(firstName.getText().toString());
feizai.setSecondName(secondName.getText().toString());
mFeizaiViewModel.update(feizai);
});
}
}
11. Rendern
PS: Wenn Anfänger Zweifel haben, können Sie die entsprechenden Details auf der offiziellen Website überprüfen.