【问题标题】:You must annotate primary keys with @NonNull?您必须用@NonNull 注释主键吗?
【发布时间】:2019-11-12 21:22:48
【问题描述】:

我在这段代码中遇到了这个错误。 You must annotate primary keys with @NonNull. "uidString" is nullable. 当我用@NonNull 和@PrimaryKey 注释它时,An entity must have at least 1 field annotated with @PrimaryKey

怎么了?

import androidx.annotation.NonNull;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;

import java.util.UUID;

@Entity(tableName = "player_profiles")
public class PlayerGameProfile implements Parcelable {

    @PrimaryKey
    public String uidString = UUID.randomUUID().toString();

    @ColumnInfo(name = "name")
    public String name;

【问题讨论】:

  • When I annotate it with @NonNull, An entity must have at least 1 field annotated with @PrimaryKey 你是用 both 还是只用 @NonNull 注释它?
  • 后者两者兼得。我也厌倦了更改订单
  • 并确保导入正确的 NonNull 包:import android.support.annotation.NonNull;
  • 是的,很抱歉粘贴了草率的代码,所有内容都存在。 OP已编辑
  • 我已经尝试了你所做的,我没有收到任何编译或构建错误。问题出在其他地方,而不是注释。另外,我使用了 AndroidX 注释和 NOT 支持注释

标签: java android android-room


【解决方案1】:

对于 Java,您应该使用 @android.support.annotation.NonNull 进行注释

删除您正在使用的另一个 NonNull 导入并将其更改为

import android.support.annotation.NonNull;

然后使用两个注解

@PrimaryKey
@NonNull

【讨论】:

    【解决方案2】:

    就我而言,我有:

    @PrimaryKey @NonNull var reasonId: String? = Constants.EMPTY_STRING, 
    
    

    代替:

    @PrimaryKey @NonNull var reasonId: String = Constants.EMPTY_STRING, 
    
    

    【讨论】:

    • 如果你正在编写 kotlin,你不应该需要@NonNull,前提是你使用了不可为空的类型
    【解决方案3】:

    您可以尝试像这样将主键与实体绑定:

    @Entity(tableName = "player_profiles",
            primaryKeys = { "uidString" })
    

    然后在下面的类中用@NonNull 注释您的主键。

    @NonNull
    public String uidString = UUID.randomUUID().toString();
    

    【讨论】:

    • :( 仍然收到关于至少 1 个主键的第二个错误
    • 另外确保您尝试我在对 OP 的评论中提到的 NonNull 的其他导入包:import android.support.annotation.NonNull
    【解决方案4】:

    检查是否区分大小写,它应该是“@NonNull”而不是“@Nonnull” 导入androidx.annotation.NonNull;

    【讨论】:

    • 其实问题中的文字就是这么说的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-09
    • 2021-09-20
    • 2021-08-25
    • 1970-01-01
    相关资源
    最近更新 更多