1,在gradle中添加依赖:

def room_version = "2.2.0-rc01"    implementation "androidx.room:room-runtime:$room_version"    annotationProcessor "androidx.room:room-compiler:$room_version"

2,创建数据库

package com.example.pagingdemo;import androidx.room.ColumnInfo;import androidx.room.Entity;import androidx.room.PrimaryKey;@Entity(tableName = "student_table")public class Student {    @PrimaryKey(autoGenerate = true)    private int id;    @ColumnInfo(name = "student_number")    private int studentNumber;    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public int getStudentNumber() {        return studentNumber;    }    public void setStudentNumber(int studentNumber) {        this.studentNumber = studentNumber;    }}

3,创建DAO

DAO,即数据访问接口。可以将SQL查询语句与方法相关联。

DAO必须是接口或抽象类。

package com.example.pagingdemo;import androidx.lifecycle.LiveData;import androidx.paging.DataSource;import androidx.room.Dao;import androidx.room.Insert;import androidx.room.Query;import java.util.List;@Daopublic interface StudentDao {//    插入    @Insert    void insertStudents(Student ...students);//    清除    @Query("DELETE FROM STUDENT_TABLE")    void deleteAllStudents();//    查询所有    @Query("SELECT * FROM STUDENT_TABLE ORDER BY ID")    LiveData> getAllStudentLive;    //DataSource.Factory getAllstudents();}

4,实现Room数据库

package com.example.pagingdemo;import android.content.Context;import androidx.room.Database;import androidx.room.Room;import androidx.room.RoomDatabase;@Database(entities = {Student.class},version = 1,exportSchema = false)public abstract class StudentsDatabase extends RoomDatabase {    private static StudentsDatabase instance;    public synchronized static StudentsDatabase getInstance(Context context) {        if(instance == null){            instance = Room.databaseBuilder(context,StudentsDatabase.class,"students_database").build();        }        return instance;    }    abstract StudentDao getStudentDao();}

5,RecyclerView提供

package com.example.pagingdemo;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView;import androidx.annotation.NonNull;import androidx.paging.PagedListAdapter;import androidx.recyclerview.widget.DiffUtil;import androidx.recyclerview.widget.RecyclerView;public class MyPagedAdapter extends PagedListAdapter {    public MyPagedAdapter() {        super(new DiffUtil.ItemCallback() {            @Override            public boolean areItemsTheSame(@NonNull Student oldItem, @NonNull Student newItem) {                return oldItem.getId() == newItem.getId();            }            @Override            public boolean areContentsTheSame(@NonNull Student oldItem, @NonNull Student newItem) {                return oldItem.getStudentNumber() == newItem.getStudentNumber();            }        });    }    @NonNull    @Override    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {        //创建视图        LayoutInflater inflater = LayoutInflater.from(parent.getContext());        View view=inflater.inflate(R.layout.cell,parent,false);        return new MyViewHolder(view);    }    @Override    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {        Student student = getItem(position);        if(student == null){            holder.textView.setText("loading");        }else{            holder.textView.setText(String.valueOf(student.getStudentNumber()));        }    }    static class MyViewHolder extends RecyclerView.ViewHolder{        TextView textView;        public MyViewHolder(@NonNull View itemView) {            super(itemView);            textView = itemView.findViewById(R.id.textView);        }    }}

6,activity实现

package com.example.pagingdemo;import androidx.appcompat.app.AppCompatActivity;import androidx.lifecycle.LiveData;import androidx.lifecycle.Observer;import androidx.paging.LivePagedListBuilder;import androidx.paging.PagedList;import androidx.paging.PagedListAdapter;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView;import android.os.AsyncTask;import android.os.Bundle;import android.view.View;import android.widget.Button;public class MainActivity extends AppCompatActivity {    RecyclerView recyclerView;    Button buttonPopulate, buttonClear;    StudentDao studentDao;    StudentsDatabase studentsDatabase;    MyPagedAdapter pagedAdapter;    LiveData> allStudentsPaged;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        //获取滚动列表,还有一个配套的adapter        recyclerView = findViewById(R.id.recyclerView);        pagedAdapter = new MyPagedAdapter();        recyclerView.setLayoutManager(new LinearLayoutManager(this));        recyclerView.setAdapter(pagedAdapter);        studentsDatabase = StudentsDatabase.getInstance(this);        studentDao = studentsDatabase.getStudentDao();        allStudentsPaged = new LivePagedListBuilder<>(studentDao.getAllstudents(), 5).build();        allStudentsPaged.observe(this, new Observer>() {            @Override            public void onChanged(PagedList students) {                pagedAdapter.submitList(students);            }        });        buttonPopulate = findViewById(R.id.buttonPopulate);        buttonClear = findViewById(R.id.buttonClear);        buttonPopulate.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                Student[] students = new Student[1000];                for (int i = 0;i {        StudentDao studentDao;        //传入数据库操作        public InsertAsyncTask(StudentDao studentDao) {            this.studentDao = studentDao;        }        @Override        protected Void doInBackground(Student... students) {            studentDao.insertStudents(students);            return null;        }    }    //清空    static class ClearAsyncTask extends AsyncTask{        StudentDao studentDao;        public ClearAsyncTask(StudentDao studentDao) {            this.studentDao = studentDao;        }        @Override        protected Void doInBackground(Void... voids) {            studentDao.deleteAllStudents();            return null;        }    }}

 

更多相关文章

  1. android 数据库初体验
  2. Android中创建文件以及文件夹
  3. Android(安卓)创建单独的服务运行在后台(无界面)
  4. Android(安卓)AlertDialog去除白色边框
  5. Android(安卓)创建菜单
  6. android 将bitmap缓存到本地
  7. android创建自定义对话框
  8. Android(安卓)封装http请求的工具类
  9. Android创建和删除桌面快捷方式

随机推荐

  1. android技巧
  2. android:inputType参数类型说明
  3. android中的style部分属性值介绍【一】
  4. 【Android】Android(安卓)设置Activity窗
  5. Android应用开发——系统自带样式Android
  6. Android(安卓)中 drawable下的 android:s
  7. android:inputType参数类型说明
  8. Android中的android:layout_width和andro
  9. Selector与Shape的基本用法
  10. Android(安卓)开发教程 (包括全部ApiDemo