![Android,LiveData+ViewModel+Room的案例_第1张图片](http://img.e-com-net.com/image/info8/883a0e0575244c7eae38852bf3abf58a.jpg)
![Android,LiveData+ViewModel+Room的案例_第2张图片](http://img.e-com-net.com/image/info8/2762a7934b8c4bd28dc2256a67c0ef00.jpg)
MainActivity.java
package com.example.app1;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private UserRecyclerViewAdapter adapter;
private UserDao userDao;
private UserViewModel userViewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
List<User> arrayList = new ArrayList<>();
adapter = new UserRecyclerViewAdapter(arrayList);
recyclerView.setAdapter(adapter);
userViewModel = new ViewModelProvider(this,new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(UserViewModel.class);
userViewModel.queryUserAllLiveData().observe(this, new Observer<List<User>>() {
@Override
public void onChanged(List<User> users) {
adapter.setList(users);
adapter.notifyDataSetChanged();
}
});
}
public void insertData(View view) {
User user1 = new User("小明",21);
User user2 = new User("小红",20);
userViewModel.insertUser(user1,user2);
}
public void deleteData(View view) {
User user1 = new User(11);
User user2 = new User(12);
userViewModel.deleteUser(user1,user2);
}
public void updateData(View view) {
User user = new User(13,"Einstein",144);
userViewModel.updateUser(user);
Toast.makeText(this, "修改成了'小明'的名字和年龄", Toast.LENGTH_SHORT).show();
}
public void mClear(View view) {
userViewModel.deleteAllUsers();
}
}
User.java:
package com.example.app1;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.Ignore;
import androidx.room.PrimaryKey;
@Entity(tableName = "user")
public class User {
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id",typeAffinity = ColumnInfo.INTEGER)
public int id;
@ColumnInfo(name = "name",typeAffinity = ColumnInfo.TEXT)
public String name;
@ColumnInfo(name = "age",typeAffinity = ColumnInfo.INTEGER)
public int age;
public User(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
@Ignore
public User(String name, int age) {
this.name = name;
this.age = age;
}
@Ignore
public User(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
UserDao.java:
package com.example.app1;
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.Update;
import java.util.List;
@Dao
public interface UserDao {
@Insert
void insert(User... users);
@Delete
void delete(User... users);
@Update
void update(User... users);
@Query("SELECT * FROM user")
LiveData<List<User>> queryAll();
@Query("DELETE FROM user")
void deleteAll();
@Query("SELECT * FROM user WHERE id = :id")
List<User> query(int id);
}
UserDatabase.java
package com.example.app1;
import android.content.Context;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
@Database(entities = {User.class},version = 1,exportSchema = false)
public abstract class UserDatabase extends RoomDatabase {
private static final String DATABASE_NAME = "user_db.db";
private static UserDatabase mInstance;
public static synchronized UserDatabase getInstance(Context context){
if (mInstance == null){
mInstance = Room.databaseBuilder(context.getApplicationContext(),
UserDatabase.class,
DATABASE_NAME)
.build();
}
return mInstance;
}
public abstract UserDao getUserDao();
}
UserRecyclerViewAdapter.java:
package com.example.app1;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class UserRecyclerViewAdapter extends RecyclerView.Adapter<UserRecyclerViewAdapter.MyViewHolder> {
private List<User> list;
public UserRecyclerViewAdapter(List<User> arrayList) {
this.list = arrayList;
}
public void setList(List<User> list) {
this.list = list;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item,parent,false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
User user = list.get(position);
TextView text_id = holder.itemView.findViewById(R.id.text_id);
text_id.setText(String.valueOf(user.id));
TextView text_name = holder.itemView.findViewById(R.id.text_name);
text_name.setText(user.name);
TextView text_age = holder.itemView.findViewById(R.id.text_age);
text_age.setText(String.valueOf(user.age));
}
@Override
public int getItemCount() {
return list.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public MyViewHolder(@NonNull View itemView) {
super(itemView);
}
}
}
UserRepository.java
package com.example.app1;
import android.content.Context;
import android.os.AsyncTask;
import androidx.lifecycle.LiveData;
import java.util.List;
public class UserRepository {
private UserDao userDao;
public UserRepository(Context context) {
UserDatabase userDatabase = UserDatabase.getInstance(context);
this.userDao = userDatabase.getUserDao();
}
public void insertUser(User... users){
new InsertUserTask(userDao).execute(users);
}
class InsertUserTask extends AsyncTask<User,Void,Void> {
private UserDao userDao;
public InsertUserTask(UserDao userDao) {
this.userDao = userDao;
}
@Override
protected Void doInBackground(User... users) {
userDao.insert(users);
return null;
}
}
public void deleteUser(User... users){
new DeleteUserTask(userDao).execute(users);
}
class DeleteUserTask extends AsyncTask<User,Void,Void>{
private UserDao userDao;
public DeleteUserTask(UserDao userDao) {
this.userDao = userDao;
}
@Override
protected Void doInBackground(User... users) {
userDao.delete(users);
return null;
}
}
public void deleteAllUsers(){
new DeleteUserAll(userDao).execute();
}
class DeleteUserAll extends AsyncTask<Void,Void,Void>{
private UserDao userDao;
public DeleteUserAll(UserDao userDao) {
this.userDao = userDao;
}
@Override
protected Void doInBackground(Void... voids) {
userDao.deleteAll();
return null;
}
}
public void updateUser(User... users){
new UpdatetUserTask(userDao).execute(users);
}
class UpdatetUserTask extends AsyncTask<User,Void,Void>{
private UserDao userDao;
public UpdatetUserTask(UserDao userDao) {
this.userDao = userDao;
}
@Override
protected Void doInBackground(User... users) {
userDao.update(users);
return null;
}
}
public LiveData<List<User>> queryUserAllLiveData(){
return userDao.queryAll();
}
}
UserViewModel.java:
package com.example.app1;
import android.app.Application;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import java.util.List;
public class UserViewModel extends AndroidViewModel {
private UserRepository userRepository;
public UserViewModel(@NonNull Application application) {
super(application);
this.userRepository = new UserRepository(application);
}
public void insertUser(User... users){
userRepository.insertUser(users);
}
public void deleteUser(User... users){
userRepository.deleteUser(users);
}
public void updateUser(User... users){
userRepository.updateUser(users);
}
public void deleteAllUsers(){
userRepository.deleteAllUsers();
}
public LiveData<List<User>> queryUserAllLiveData(){
return userRepository.queryUserAllLiveData();
}
}
activity_main.xml:
<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=".MainActivity">
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.41" />
<Button
android:id="@+id/insertBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="76dp"
android:layout_marginBottom="92dp"
android:text="添加数据"
app:layout_constraintBottom_toTopOf="@+id/guideline5"
app:layout_constraintStart_toStartOf="parent"
android:onClick="insertData"/>
<Button
android:id="@+id/deleteBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="76dp"
android:layout_marginBottom="32dp"
android:text="删除数据"
app:layout_constraintBottom_toTopOf="@+id/guideline5"
app:layout_constraintStart_toStartOf="parent"
android:onClick="deleteData"/>
<Button
android:id="@+id/updateBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="68dp"
android:layout_marginBottom="92dp"
android:text="修改数据"
app:layout_constraintBottom_toTopOf="@+id/guideline5"
app:layout_constraintEnd_toEndOf="parent"
android:onClick="updateData"/>
<Button
android:id="@+id/mClear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="68dp"
android:layout_marginBottom="32dp"
android:text="清空数据"
app:layout_constraintBottom_toTopOf="@+id/guideline5"
app:layout_constraintEnd_toEndOf="parent"
android:onClick="mClear"/>
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="184dp"
android:background="#03A9F4"
android:text="数据库的相关操作"
android:textSize="34sp"
app:layout_constraintBottom_toTopOf="@+id/guideline5"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.527" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="370dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/guideline5"
app:layout_constraintVertical_bias="0.38" />
androidx.constraintlayout.widget.ConstraintLayout>
item.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/text_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#03A9F4"
android:text="id"
android:gravity="center"
android:textSize="34sp"/>
<TextView
android:id="@+id/text_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#FFC107"
android:text="名字"
android:gravity="center"
android:textSize="34sp"/>
<TextView
android:id="@+id/text_age"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#FF5722"
android:text="年龄"
android:gravity="center"
android:textSize="34sp"/>
LinearLayout>