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


目录
相关文章
|
9月前
|
数据库 Android开发
Android使用EditText+Listview实现搜索效果(使用room模糊查询)
本文介绍如何在Android中使用EditText与ListView实现搜索功能,并结合Room数据库完成模糊查询。主要内容包括:Room的模糊查询语句(使用`||`代替`+`号)、布局美化(如去除ListView分割线和EditText下划线)、EditText回车事件监听,以及查询逻辑代码示例。此外,还提供了相关扩展文章链接,帮助读者深入了解ListView优化、动态搜索及Room基础操作。
611 65
|
9月前
|
XML 数据库 Android开发
Android数据库的使用(增删改查)
本文介绍了一个简单的数据库操作Demo,包含创建数据库、增删改查功能。通过5个按钮分别实现创建数据库、插入数据、删除数据、更新数据和查询数据的操作。代码结构清晰,适合初学者学习Android SQLite数据库基础操作。
276 5
|
9月前
|
数据库 Android开发
Android外部数据库的引用
简介:本文介绍了在Android项目中引用外部数据库的方法。首先,将现成的数据库文件放入项目的`assets`文件夹中(需手动创建)。其次,在APP引导界面通过代码将数据库拷贝至App目录下,确保数据库可用。最后,对数据库进行增删改查等操作。关键步骤包括判断数据库是否存在、使用`AssetManager`读取数据库文件并写入App私有目录,实现外部数据库的顺利集成与使用。
119 2
|
9月前
|
数据库 Android开发 开发者
Android常用的room增删改查语句(外部数据库)
本文分享了将一个原生数据库驱动的单词APP重构为使用Room库的过程及遇到的问题,重点解决了Room中增删改查的常用语句实现。文章通过具体示例(以“forget”表为例),详细展示了如何定义实体类、Dao接口、Database类以及Repository和ViewModel的设计与实现。同时,提供了插入、删除、更新和查询数据的代码示例,包括模糊查询、分页加载等功能。此外,针对外部数据库导入问题,作者建议可通过公众号“计蒙不吃鱼”获取更多支持。此内容适合有一定Room基础的开发者深入学习。
293 0
Android常用的room增删改查语句(外部数据库)
|
消息中间件 数据采集 数据库
小说爬虫-03 爬取章节的详细内容并保存 将章节URL推送至RabbitMQ Scrapy消费MQ 对数据进行爬取后写入SQLite
小说爬虫-03 爬取章节的详细内容并保存 将章节URL推送至RabbitMQ Scrapy消费MQ 对数据进行爬取后写入SQLite
250 1
|
存储 API 数据库
QML使用Sqlite数据库存储ListModel数据
本文介绍了在QML中使用Sqlite数据库存储ListModel数据的方法,包括如何创建数据库、读取数据、动态添加和删除数据,以及如何在程序启动和退出时与数据库同步数据。
454 2
|
Android开发
Android kernel 操作gpio
Android kernel 操作gpio
287 0
|
存储 缓存 数据库
Android之SQLite数据库使用详解
Android之SQLite数据库使用详解
1338 0
|
存储 算法 Java
Android 进阶——代码插桩必知必会&ASM7字节码操作
Android 进阶——代码插桩必知必会&ASM7字节码操作
1371 0
|
存储 数据库连接 数据库
Android数据存储:解释SQLite数据库在Android中的使用。
Android数据存储:解释SQLite数据库在Android中的使用。
280 0

热门文章

最新文章