在基于MVVM的应用程序中添加Room Database类会产生绑定问题

时间:2018-05-17 11:32:25

标签: android android-databinding android-room

我在基于MVVM的Android应用中使用Room Database。我面临的问题是,无论何时我将数据库文件放入代码中,应用程序都会开始提供DataBinding错误,并在删除该文件时删除所有错误。我还没有在AppModule文件中声明它,它开始给出错误。有什么问题?

数据库类:

@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {

    public abstract UserDao userDao();

}

以下是Dao:

    @Dao
    public interface UserDao {

        @Query("SELECT * FROM User WHERE userId =:id")
        User findUserById(String id);
}

以下是用户模型:

@Entity
public class User implements Serializable {

    @PrimaryKey
    private int userId;

    private String username;

    private String fullName;

    @Ignore
    private boolean isLive;

    private String createdAt;

    @Ignore
    private boolean requestSent;
    @Ignore
    private boolean isFollowed;

    private String picture;

    private String name;
    @Ignore
    private boolean isFollow;

    private String phone;
}

1 个答案:

答案 0 :(得分:0)

Please inject inside a AppDatabase class

 /** The AppDatabase instance */
private static AppDatabase mInstance;

/**
 * Gets the singleton instance of AppDatabase.
 *
 * @param context The context.
 * @return The singleton instance of AppDatabase.
 */
public static AppDatabase getDatabaseInstance(Context context)
{
    if (mInstance == null)
    {                                                                           /* The name of the Database table. */
        mInstance = Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, "databaseTableName")).build();
    }

    return mInstance;
}


    And make sure to use Cursor not User to findUserById

    @Query("SELECT * FROM User WHERE userId =:id")
    Cursor findUserById(String id);