当尝试使用文件室库处理数据库时,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;
}
}
1条答案
按热度按时间svgewumm1#
你的
db
属于类型RoomDatabase
.RoomDatabase
没有一个itemDao()
方法,你的MyDatabase
扩展它有。所以这个字段应该是MyDatabase
如果你想访问itemDao()