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操作数据库的相关知识!


目录
相关文章
|
5天前
|
SQL 存储 关系型数据库
数据储存数据库管理系统(DBMS)
【10月更文挑战第11天】
13 3
|
10天前
|
SQL 存储 关系型数据库
添加数据到数据库的SQL语句详解与实践技巧
在数据库管理中,添加数据是一个基本操作,它涉及到向表中插入新的记录
|
14天前
|
SQL 监控 数据处理
SQL数据库数据修改操作详解
数据库是现代信息系统的重要组成部分,其中SQL(StructuredQueryLanguage)是管理和处理数据库的重要工具之一。在日常的业务运营过程中,数据的准确性和及时性对企业来说至关重要,这就需要掌握如何在数据库中正确地进行数据修改操作。本文将详细介绍在SQL数据库中如何修改数据,帮助读者更好
73 4
|
15天前
|
存储 人工智能 Cloud Native
云栖重磅|从数据到智能:Data+AI驱动的云原生数据库
阿里云瑶池在2024云栖大会上重磅发布由Data+AI驱动的多模数据管理平台DMS:OneMeta+OneOps,通过统一、开放、多模的元数据服务实现跨环境、跨引擎、跨实例的统一治理,可支持高达40+种数据源,实现自建、他云数据源的无缝对接,助力业务决策效率提升10倍。
|
16天前
|
关系型数据库 MySQL 数据库
使用Docker部署的MySQL数据库,数据表里的中文读取之后变成问号,如何处理?
【10月更文挑战第1天】使用Docker部署的MySQL数据库,数据表里的中文读取之后变成问号,如何处理?
42 3
|
15天前
|
测试技术 API 数据库
云数据库之添加数据
云数据库之添加数据
17 1
|
16天前
|
存储 关系型数据库 MySQL
MySQL数据库数据块大小
MySQL数据库数据块大小
33 1
|
9天前
|
存储 大数据 数据库
Android经典面试题之Intent传递数据大小为什么限制是1M?
在 Android 中,使用 Intent 传递数据时存在约 1MB 的大小限制,这是由于 Binder 机制的事务缓冲区限制、Intent 的设计初衷以及内存消耗和性能问题所致。推荐使用文件存储、SharedPreferences、数据库存储或 ContentProvider 等方式传递大数据。
10 0
|
17天前
|
存储 监控 关系型数据库
MySQL数据库数据块大小详解
MySQL数据库数据块大小详解
35 0
|
9天前
|
存储 SQL 关系型数据库
Mysql学习笔记(二):数据库命令行代码总结
这篇文章是关于MySQL数据库命令行操作的总结,包括登录、退出、查看时间与版本、数据库和数据表的基本操作(如创建、删除、查看)、数据的增删改查等。它还涉及了如何通过SQL语句进行条件查询、模糊查询、范围查询和限制查询,以及如何进行表结构的修改。这些内容对于初学者来说非常实用,是学习MySQL数据库管理的基础。
43 6