错误:不确定如何将游标转换为此方法的返回类型(com.madstone.tageditor.database.TrackFileAndSong)

mv1qrgav  于 2022-10-09  发布在  Android
关注(0)|答案(1)|浏览(89)

在Android Studio中构建项目时,我收到以下错误
错误:不确定如何将游标转换为此方法的返回类型(com.madstone.tageditor.database.TrackFileAndSong).LiveDatagetTrackFileAndSong();

我正在尝试使用中间数据类TrackFileAndSong从房间数据库中获取相关的TrackFile和Song对象,并将返回的对象存储为LiveData

曲目文件:

@Entity(tableName = "track_file_table")
public class TrackFile {
    @PrimaryKey(autoGenerate = true)
    public long id;

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

    @ColumnInfo(name = "track_path")
    public String trackFilePath;
}

歌曲:

@Entity(tableName = "song_table")
public class Song {

    @PrimaryKey(autoGenerate = true)
    public long songId;

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

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

    @ColumnInfo(name = "Album Artist")
    public String songAlbumArtist;

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

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

    public long fileId;

}

TrackFileAndSong:

public class TrackFileAndSong {
    @Embedded
    public TrackFile trackFile;
    @Relation(
            parentColumn = "id",
            entityColumn = "fileId"
    )
    public Song song;
}

在此查询中抛出错误

@Transaction
    @Query("SELECT * FROM song_table ORDER BY Title ASC")
    LiveData<List<TrackFileAndSong>> getTrackFileAndSong();

如有任何帮助,我们将不胜感激

cyvaqqii

cyvaqqii1#

原因是你所说的话大致如下:

从Song_table中获取trackFileAndSong列表,这等同于从Song_table中获取所有TrackFiles(Parents Ak Embedded)(然后从Song_table中获取歌曲,子对象又称为@Relation)

  • 显然,Song_table中没有TrackFiles(因此,您告诉Room从Song_table中的一行获取TrackFiles时,Room会感到困惑)。

因此,要使用TrackFileAndSong,那么您应该使用FROM track_file_table,当然,ORDER BY子句没有标题列。

因此,以下内容至少可以绕过错误:

@Transaction
@Query("SELECT * FROM track_file_table")
LiveData<List<TrackFileAndSong>> getTrackFileAndSong();

然而,它可能是您真正想要的(例如)

class SongAndTrackFile {
   @Embedded
    Song song;
    @Relation(
            entity = TrackFile.class,
            parentColumn = "fileId",
            entityColumn = "id"
    )
    TrackFile trackFile;
}
  • 即@Embedded(父级)和@Relation(子级)已互换。

在这种情况下,下列措施将会奏效:

@Transaction
@Query("SELECT * FROM song_table ORDER BY Title ASC")
LiveData<List<SongAndTrackFile /*!!!!!<<<<< NOTE CHANGED Type!!!!!*/>> getSongAndTrackFile();
  • 显然,你不需要仅仅为了表明与原始版本的变化而添加评论

相关问题