Android使用Room操作SQLite数据库让其变得无比高效和简洁(进一步完善用RecyclerView显示数据库中的数据)

简介: Android使用Room操作SQLite数据库让其变得无比高效和简洁(进一步完善用RecyclerView显示数据库中的数据)

前言:没看前两篇文章的可以先去看下前两篇文章

传送门:

Android 使用Room操作SQLite数据库让其变得无比高效和简洁(教程一)

Android 使用Room操作SQLite数据库让其变得无比高效和简洁(前一篇文章的完善)

下一篇文章数据库版本的升级,迁移

Android 使用Room操作数据库进行数据库版本的升级和迁移

将其数据展示更换成RecyclerView

activity_main.xml代码如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycle_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:orientation="vertical">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:gravity="center"
            android:orientation="horizontal">
            <Button
                android:id="@+id/btn_insert"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="添加" />
            <Switch
                android:id="@+id/switch1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp" />
            <Button
                android:id="@+id/btn_clear"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="50dp"
                android:layout_weight="1"
                android:text="清除" />
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

之后写RecyclerView的子布局,这里我们用两种布局第一种是正常显示的列表布局,第二种用卡片式布局用到了CardView

第一种布局item_word.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="80dp"
    android:background="?selectableItemBackground"
    android:clickable="true"
    android:orientation="horizontal">
    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="80dp"
        android:layout_weight="1"
        android:gravity="center">
        <TextView
            android:id="@+id/tv_id"
            android:layout_width="80dp"
            android:layout_height="80dp" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="80dp"
        android:layout_weight="5"
        android:orientation="vertical">
        <TextView
            android:id="@+id/tv_english"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1" />
        <TextView
            android:id="@+id/tv_chinese"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:height="0dp" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="80dp"
        android:layout_weight="1"
        android:gravity="center">
        <ImageView
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_marginRight="10dp"
            android:src="@drawable/ic_baseline_chevron_right_24" />
    </LinearLayout>
</LinearLayout>

第二种布局item_card.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:background="?selectableItemBackground"
    android:clickable="true">
    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:layout_marginStart="10dp"
        android:layout_marginTop="10dp"
        android:layout_marginEnd="10dp">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="80dp"
            android:orientation="horizontal">
            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:gravity="center">
                <TextView
                    android:id="@+id/tv_id"
                    android:layout_width="80dp"
                    android:layout_height="80dp"
                    android:gravity="center" />
            </LinearLayout>
            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="80dp"
                android:layout_weight="5"
                android:orientation="vertical">
                <TextView
                    android:id="@+id/tv_english"
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="1" />
                <TextView
                    android:id="@+id/tv_chinese"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:height="0dp" />
            </LinearLayout>
            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="80dp"
                android:layout_weight="1"
                android:gravity="center">
                <ImageView
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:src="@drawable/ic_baseline_chevron_right_24" />
            </LinearLayout>
        </LinearLayout>
    </androidx.cardview.widget.CardView>
</LinearLayout>

这两个我们都在最外层布局中加上了两个属性

android:background="?selectableItemBackground"
android:clickable="true"

加上这两个属性后,用户点击数据列表时,会有一个阴影的一个效果,使用户有更好的体验。

之后创建一个适配器MyAdapter,通过适配器把数据渲染到页面上面

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
    private List<Word> allWords = new ArrayList<>();
    boolean userCardView;
    public MyAdapter(boolean userCardView) {
        this.userCardView = userCardView;
    }
    public void setAllWords(List<Word> allWords) {
        this.allWords = allWords;
    }
    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view;
        if (userCardView) {
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_card, parent, false);
        } else {
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_word, parent, false);
        }
        return new MyViewHolder(view);
    }
    @Override
    public int getItemCount() {
        return allWords.size();
    }
    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        Word word = allWords.get(position);
        holder.tv_id.setText(String.valueOf(position + 1));
        holder.tv_english.setText(word.getWord());
        holder.tv_chinese.setText(word.getChineseMeaning());
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Uri uri = Uri.parse("https://m.youdao.com/dict?le=eng&q=" + holder.tv_english.getText());
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(uri);
                holder.itemView.getContext().startActivity(intent);
            }
        });
    }
    public class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView tv_id;
        public TextView tv_english;
        public TextView tv_chinese;
        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            tv_id = itemView.findViewById(R.id.tv_id);
            tv_english = itemView.findViewById(R.id.tv_english);
            tv_chinese = itemView.findViewById(R.id.tv_chinese);
        }
    }
}

最后在MainActivity中调用适配器,把数据呈现个用户

public class MainActivity extends AppCompatActivity {
    private Button btn_insert, btn_clear, btn_update, btn_delete;
    private WordViewModel wordViewModel;
    private RecyclerView recycle_view;
    private MyAdapter myAdapter1, myAdapter2;
    private Switch switch1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn_insert = findViewById(R.id.btn_insert);
        btn_clear = findViewById(R.id.btn_clear);
//        btn_update = findViewById(R.id.btn_update);
//        btn_delete = findViewById(R.id.btn_delete);
        switch1 = findViewById(R.id.switch1);
        recycle_view = findViewById(R.id.recycle_view);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        recycle_view.setLayoutManager(linearLayoutManager);
        myAdapter1 = new MyAdapter(false);
        myAdapter2 = new MyAdapter(true);
        switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                if (isChecked) {
                    recycle_view.setAdapter(myAdapter2);
                } else {
                    recycle_view.setAdapter(myAdapter1);
                }
            }
        });
        wordViewModel = ViewModelProviders.of(this).get(WordViewModel.class);
        wordViewModel.getAllWordsLive().observe(this, new Observer<List<Word>>() {
            @Override
            public void onChanged(List<Word> words) {
                myAdapter1.setAllWords(words);
                myAdapter1.notifyDataSetChanged();
                myAdapter2.setAllWords(words);
                myAdapter2.notifyDataSetChanged();
            }
        });
        recycle_view.setAdapter(myAdapter1);
        btn_insert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String[] english = {"Hello", "World", "Android", "Google", "Studio", "Project"
                        , "DataBase", "Recycler", "View", "String", "Value", "Integer"
                };
                String[] chinese = {"你好", "世界", "安卓系统", "谷歌公司", "工作室", "项目", "数据库", "回收站"
                        , "视图", "字符串", "价值", "整数类型"
                };
                for (int i = 0; i < english.length; i++) {
                    Word word1 = new Word(english[i], chinese[i]);
                    wordViewModel.insertWords(word1);
                }
            }
        });
        btn_clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                wordDao.deleteAllWords();
                wordViewModel.deleteAllWords();
            }
        });
    }
}

效果如图所示:

点击下方按钮可以实现切换布局样式的功能~ 持续更新Room操作数据库的相关知识!


目录
相关文章
|
存储 数据库 开发者
Python SQLite模块:轻量级数据库的实战指南
本文深入讲解Python内置sqlite3模块的实战应用,涵盖数据库连接、CRUD操作、事务管理、性能优化及高级特性,结合完整案例,助你快速掌握SQLite在小型项目中的高效使用,是Python开发者必备的轻量级数据库指南。
1111 0
|
数据库 Android开发 开发者
Android常用的room增删改查语句(外部数据库)
本文分享了将一个原生数据库驱动的单词APP重构为使用Room库的过程及遇到的问题,重点解决了Room中增删改查的常用语句实现。文章通过具体示例(以“forget”表为例),详细展示了如何定义实体类、Dao接口、Database类以及Repository和ViewModel的设计与实现。同时,提供了插入、删除、更新和查询数据的代码示例,包括模糊查询、分页加载等功能。此外,针对外部数据库导入问题,作者建议可通过公众号“计蒙不吃鱼”获取更多支持。此内容适合有一定Room基础的开发者深入学习。
476 0
Android常用的room增删改查语句(外部数据库)
|
SQL 数据库连接 数据库
在C++的QT框架中实现SQLite数据库的连接与操作
以上就是在C++的QT框架中实现SQLite数据库的连接与操作的基本步骤。这些步骤包括创建数据库连接、执行SQL命令、处理查询结果和关闭数据库连接。在实际使用中,你可能需要根据具体的需求来修改这些代码。
1059 14
|
关系型数据库 MySQL 数据库
Python处理数据库:MySQL与SQLite详解 | python小知识
本文详细介绍了如何使用Python操作MySQL和SQLite数据库,包括安装必要的库、连接数据库、执行增删改查等基本操作,适合初学者快速上手。
1594 15
|
数据库
【YashanDB数据库】yasboot查询数据库状态时显示数据库状态为off
yasboot查询数据库状态时显示数据库状态为off
|
存储 SQL 数据库
数据库知识:了解SQLite或其他移动端数据库的使用
【10月更文挑战第22天】本文介绍了SQLite在移动应用开发中的应用,包括其优势、如何在Android中集成SQLite、基本的数据库操作(增删改查)、并发访问和事务处理等。通过示例代码,帮助开发者更好地理解和使用SQLite。此外,还提到了其他移动端数据库的选择。
617 8
|
Web App开发 SQL 数据库
使用 Python 解析火狐浏览器的 SQLite3 数据库
本文介绍如何使用 Python 解析火狐浏览器的 SQLite3 数据库,包括书签、历史记录和下载记录等。通过安装 Python 和 SQLite3,定位火狐数据库文件路径,编写 Python 脚本连接数据库并执行 SQL 查询,最终输出最近访问的网站历史记录。
679 4
|
存储 缓存 关系型数据库
sqlite 数据库 介绍
sqlite 数据库 介绍
714 0
|
缓存 关系型数据库 BI
使用MYSQL Report分析数据库性能(下)
使用MYSQL Report分析数据库性能
797 158
|
关系型数据库 MySQL 数据库
自建数据库如何迁移至RDS MySQL实例
数据库迁移是一项复杂且耗时的工程,需考虑数据安全、完整性及业务中断影响。使用阿里云数据传输服务DTS,可快速、平滑完成迁移任务,将应用停机时间降至分钟级。您还可通过全量备份自建数据库并恢复至RDS MySQL实例,实现间接迁移上云。