如何存储和检索以在 Room 数据库上显示表情符号 (Android Studio)

如何解决如何存储和检索以在 Room 数据库上显示表情符号 (Android Studio)

我正在使用带有 Java 语言的 Room 数据库构建情绪跟踪器 android 应用程序。 我打算使用 android 内置的表情符号让用户输入他们想要的表情符号,但我不确定如何将它存储在 Room db 中,然后检索数据以显示在另一个片段中?

如果有人能就此提供一些指导或附上相关的教程视频链接,我将不胜感激,因为我对移动应用程序开发还是个新手

解决方法

就 Room 而言,您只需要存储一些知道表情符号是什么的方法,也许是表情符号的 Unicode。

例如笑脸是0x1F600,也许是描述性的。然后,您可以设置 TextView,例如,合并表情符号。

也许你可以有一个只包含表情符号的表格,然后存储对这个表格的引用(有关系)。

下面是一个非常简单的 Room 示例。

结果将是显示在 ListView 中的表情符号列表。

这个例子有一个表,其中存储了表情符号代码以及表情符号的描述。该表已命名为 emoji,实体类为 EmojiTable,如下所示:-

@Entity(tableName = "emoji")
class EmojiTable {
    @PrimaryKey(autoGenerate = false)
    @ColumnInfo(name = "_id")
    Long id;
    @ColumnInfo(name = "emoji_code",index = true)
    String emoji_code;
    @ColumnInfo(name = "emojidesc")
    String emoji_desc;

    // Default constructor
    EmojiTable(){}

    // Alternative Constructor
    @Ignore
    EmojiTable(String emoji_code,String emoji_desc) {
        this.emoji_code = emoji_code;
        this.emoji_desc = emoji_desc;
    }

    // Override default toString method to return the emoji followed by it's decsription
    @Ignore
    public String toString() {
        return new String(Character.toChars(Integer.decode(emoji_code))) + " " + emoji_desc;
    }
}
  • 3 列
    • 唯一标识符的 _id
    • 用于表情符号十六进制代码的 emoji_code
    • 用于描述表情符号的 emoji_desc
  • 请注意,toString 方法已被覆盖,以返回一个包含表情符号及其说明的字符串。这个是用来设置ListView中的TextView的。
    • 否则将使用默认的 toString 方法来显示对象。

为了配合表情符号表,数据库操作的 DAO AllDao :-

@Dao
interface AllDao {
    
    // Insertion of a row
    @Insert(entity = EmojiTable.class,onConflict = OnConflictStrategy.IGNORE)
    long insertEmoji(EmojiTable e);
    //Deletion of ALL rows
    @Query("DELETE FROM emoji")
    int deleteAll();
    // Get ALL rows
    @Query("SELECT * FROM emoji")
    List<EmojiTable> getAllEmojis();
    // Get a row by the id passed to the method 
    @Query("SELECT * FROM emoji WHERE emoji._id = :id")
    EmojiTable getEmojiById(Long id);
    // Get the number of rows (used to detect changes)
    @Query("SELECT count(*) FROM emoji")
    Long getRowsInEmojiTable();
}

@Database 抽象类MyDatabase

@Database(entities = {EmojiTable.class},version = 1)
abstract class MyDatabase extends RoomDatabase {
    abstract AllDao getAllDao();
}

一个类,即定义表情符号/表情符号主列表的EmojiList。

  • 使用此更改(如果表情符号的更改数量)允许更改存储在数据库中的表情符号(应部署新版本的应用)。

.

class EmojiList {

    public static final EmojiTable[] EMOJIS =  {
            new EmojiTable("0x1F600","Grinning Face"),new EmojiTable("0x1F602","Unknown"),new EmojiTable("0x1F911","Money-Mouth Face")
    };
}
  • 定义了 3 个表情符号

包含用于显示表情符号列表的 ListView 的布局:-

<?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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        />

    <ListView
        android:id="@+id/emojilist"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/design_default_color_secondary"/>

</LinearLayout>
  • 这里没有什么特别的,只是通过背景颜色来查看列表的位置。

最后把它们放在一起MainActivity

public class MainActivity extends AppCompatActivity {

    MyDatabase db;
    AllDao dao;
    List<EmojiTable> emojiList_list;
    ListView emojiList_listview;
    ArrayAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        // Instantiate the MyDatabase object with a built Room Database
        db = Room.databaseBuilder(this,MyDatabase.class,"mydb")
                .allowMainThreadQueries()
                .build();
        // Instantiate the dao interface
        dao = db.getAllDao();
        // Check to see if the emoji's stored equals the master list
        // If not rebuild the emjoi table
        if (dao.getRowsInEmojiTable() != EmojiList.EMOJIS.length) {
            dao.deleteAll(); // Delete all existing rows
            for(EmojiTable e: EmojiList.EMOJIS) {
                dao.insertEmoji(e);
            }
        }
        // Very simple list of all emojis
        emojiList_list = dao.getAllEmojis(); // 
        emojiList_listview = this.findViewById(R.id.emojilist);
        adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,emojiList_list);
        emojiList_listview.setAdapter(adapter);
    }
}

结果

运行时应用程序看起来像:-

enter image description here

数据库(通过数据库检查器):-

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-