美文网首页Android开发Android开发经验谈Android开发
Android: Jetpack 按需从数据源加载数据——Pa

Android: Jetpack 按需从数据源加载数据——Pa

作者: 壹零二肆 | 来源:发表于2020-05-09 14:26 被阅读0次
    paging架构
    Jetpack 组件集

    Paging

    • 支持分页加载数据

    • 支持有限或者无限的 数据源

    • RecyclerView集成,提供PagedListAdapter

    • LiveData 或者 RxJava 集成


    使用

    逻辑: RecyclerView --> PagedListAdapter --> PagedList --> LivePagedListBuilder --> DataSourceFactory --> Room Dao返回

    • 搭配Room为数据源,在Dao中设计方法返回DataSource.Factory<Integer,Student>

    • 使用RecyclerView 作为容器,设计类继承PagedListAdapter<Student,MyViewHolder>

    • 此外使用AsyncTask来进行数据库操作或者联网操作

    (其中的 Student 为Room 中 Entry类)


    元素


    DataSource

    DataSource
    DataSource.Factory Room 可直接返回该类型,提供数据库的DataSource

    LivePagedListBuilder


    接受 DataSourceFactorypageSize 参数 返回一个 LiveData<PagedList<>>

    PagedListAdapter

    无论什么复杂的结构。1 . Adapter始终 输入数据 进行适配 2 . 注意泛型

    获取 pagedList 提供给 RecyclerView 显示

    submit方法提供 最新pagedList 数据

    总结

    code lab官方

    代码

    目录结构
    MainActivity View层
    
    public class MainActivity extends AppCompatActivity {
    
        RecyclerView recyclerView;
        Button btnGenerate, btnClear;
        StudentDao studentDao;
        StudentDatabase studentDatabase;
        MainPageAdapter mainPageAdapter;
        LiveData<PagedList<Student>> allStudentsLive;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            mainPageAdapter = new MainPageAdapter();
            recyclerView = findViewById(R.id.recyclerView);
            btnGenerate = findViewById(R.id.btnGernerate);
            btnClear = findViewById(R.id.btnClear);
    
            recyclerView.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
            recyclerView.setAdapter(mainPageAdapter);
            studentDao = StudentDatabase.getInstance(this).getStudentDao();
            allStudentsLive = new LivePagedListBuilder<>(studentDao.getAllStudents(), 2).build();
            allStudentsLive.observe(this, new Observer<PagedList<Student>>() {
                @Override
                public void onChanged(final PagedList<Student> students) {
                    mainPageAdapter.submitList(students);
                    //  添加一些 callback 监听  数据的变化
                    students.addWeakCallback(null, new PagedList.Callback() {
                        @Override
                        public void onChanged(int position, int count) {
                            Log.d("gongshijie", "此时的students数据:" + students + "count:" + count);
                        }
    
                        @Override
                        public void onInserted(int position, int count) {
    
                        }
    
                        @Override
                        public void onRemoved(int position, int count) {
    
                        }
                    });
                }
            });
    
            btnGenerate.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Student[] students = new Student[1000];
                    for (int i = 0; i < 1000; i++) {
                        Student student = new Student();
                        student.setStudentNumber(i);
                        students[i] = student;
                    }
                    new InsertAsyncTask(studentDao).execute(students);
                }
            });
    
            btnClear.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    new ClearAsyncTask(studentDao).execute();
                }
            });
    
        }
    
    
        static class InsertAsyncTask extends AsyncTask<Student, Void, Void> {
            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<Void, Void, Void> {
            StudentDao studentDao;
    
            public ClearAsyncTask(StudentDao studentDao) {
                this.studentDao = studentDao;
            }
    
            @Override
            protected Void doInBackground(Void... voids) {
                studentDao.deleteAllStudent();
                return null;
            }
        }
    }
    

    Adapter层

    
    public class MainPageAdapter extends PagedListAdapter<Student, MainPageAdapter.MyViewHolder> {
    
    
        protected MainPageAdapter() {
            super(new DiffUtil.ItemCallback<Student>() {
                @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 MainPageAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            LayoutInflater inflater = LayoutInflater.from(parent.getContext());
            View view = inflater.inflate(R.layout.item, parent, false);
            return new MyViewHolder(view);
        }
    
        @Override
        public void onBindViewHolder(@NonNull MainPageAdapter.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);
            }
        }
    }
    
    

    StudentDao Room层

    
    @Dao
    public interface StudentDao {
        @Insert
        void insertStudents(Student ... students);
        @Query("DELETE FROM STUDENT_TABLE")
        void deleteAllStudent();
        @Query("SELECT * FROM STUDENT_TABLE ORDER BY ID")
        DataSource.Factory<Integer,Student> getAllStudents();
    }
    
    

    Room database

    
    @Database(entities = {Student.class}, version = 1, exportSchema = false)
    public abstract class StudentDatabase extends RoomDatabase {
        public abstract StudentDao getStudentDao();
    
        private static StudentDatabase INSTANCE;
        //双重检查  创建单例  支持并发   懒加载
        public static StudentDatabase getInstance(Context context) {
            if (INSTANCE == null) {
                synchronized (StudentDatabase.class) {
                    if (INSTANCE == null) {
                        INSTANCE = Room.databaseBuilder(context.getApplicationContext(), StudentDatabase.class, "student_db").
                                build();
                    }
    
                }
            }
            return INSTANCE;
        }
    }
    
    

    分析

    pagesize == 1000
    pagesize == 2 分享 成长

    相关文章

      网友评论

        本文标题:Android: Jetpack 按需从数据源加载数据——Pa

        本文链接:https://www.haomeiwen.com/subject/wghknhtx.html