room数据库示例无法解析dao方法的符号

oaxa6hgo  于 2021-07-11  发布在  Java
关注(0)|答案(1)|浏览(472)

当尝试使用文件室库处理数据库时,android studio无法解析mainactivity中itemdao()方法的符号:

db.itemDao().insert(item);

主活动.java

public class MainActivity extends AppCompatActivity {

    Button btn;
    EditText et;
    TextView tv;
    RoomDatabase db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn = findViewById(R.id.button);
        et = findViewById(R.id.editText);
        tv = findViewById(R.id.textView);

        db = MyDatabase.getInstance(this);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Item item = new Item();
                item.info = et.getText().toString();
                tv.setText(item.info);
                db.itemDao().insert(item);
            }
        });
    }
}

项目.java

@Entity(tableName = "tableItems")
public class Item {
    @PrimaryKey(autoGenerate = true)
    public int uid;

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

项目DAO.java

@Dao
public interface ItemDao {
    @Query("SELECT * FROM tableItems")
    List<Item> getItemsList();

    @Insert
    void insert(Item item);

    @Delete
    void delete(Item item);
}

我的数据库.java

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

    public abstract ItemDao itemDao();
    private static MyDatabase INSTANCE;
    private static final String DATABASE_NAME = "MyDatabase";

    public synchronized static MyDatabase getInstance(Context context) {
        if (INSTANCE == null) {
            INSTANCE = Room.databaseBuilder(context.getApplicationContext(), MyDatabase.class, DATABASE_NAME)
                    .allowMainThreadQueries()
                    .build();
        }
        return INSTANCE;
    }
}
svgewumm

svgewumm1#

你的 db 属于类型 RoomDatabase . RoomDatabase 没有一个 itemDao() 方法,你的 MyDatabase 扩展它有。所以这个字段应该是 MyDatabase 如果你想访问 itemDao()

相关问题