我正在将Room Persistance Library用于我的数据库。我的一个查询返回null,但我不明白为什么:
实体:
@Entity
public class Item{
@PrimaryKey (autoGenerate = true)
@ColumnInfo (name = "I_ID")
private final int iId;
@ColumnInfo (name = "I_Name")
private final String iName;
public int getIId() {
return iId;
}
public String getIName() {
return iName;
}
public Item(int iId, String iName) {
this.iId = iId;
this.iName = iName;
}
}
道:
@Dao
public interface ItemDao {
@Query("SELECT * FROM Item WHERE I_ID = :iId")
Item getItemById(int iId);
}
此查询显示警告:Return value of the method is never used
。
即使我确定数据库中存在具有给定ID的项目,它也始终返回null。有人可以帮我吗?
答案 0 :(得分:0)
我发现尝试这样使用:
<script>
export default {
methods: {
window: (onload = function() {
const id = this.$route.params.id;
})
}
};
</script>
答案 1 :(得分:0)
给定的代码似乎没有问题。而是您没有检查可能的结果,即由于id并非Item的id而没有返回任何内容。
使用上面的Item类,并按照:-
稍加修改的ItemDao(允许插入)@Dao
public interface ItemDao {
@Query("SELECT * FROM Item WHERE I_ID = :iId")
Item getItemById(int iId);
@Insert
long insert(Item item); //<<<<<<<<<< ADDED
}
@Database为:-
@androidx.room.Database(version = 1,entities = {Item.class})
public abstract class Database extends RoomDatabase {
public abstract ItemDao itemDao();
}
以及活动中的以下代码:-
public class MainActivity extends AppCompatActivity {
Database mDB;
ItemDao mItemDao;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDB = Room.databaseBuilder(this,Database.class,"mydb")
.allowMainThreadQueries()
.build();
mItemDao = mDB.itemDao();
mItemDao.insert(new Item(1,"Item1"));
mItemDao.insert(new Item(2,"Item2"));
logItemInfo(mItemDao.getItemById(1));
logItemInfo(mItemDao.getItemById(2));
}
private void logItemInfo(Item i) {
Log.d("ITEMINFO","Item is " + i.getIName() + " ID is " + i.getIId());
}
}
日志中的结果输出为:-
2019-10-02 07:36:41.180 D/ITEMINFO: Item is Item1 ID is 1
2019-10-02 07:36:41.181 D/ITEMINFO: Item is Item2 ID is 2
您似乎遇到的问题是,您可能会将一个id传递给选择的对象,而该id实际上并不是正在使用的id。
例如使用:-
mItemDao.deleteAllItems(); //<<<<<<<<<<< Added to Item Dao as @Query("DELETE FROM Item") to make this rerunnable
mItemDao.insert(new Item(1,"Item1")); //<<<<<<<<<< AS WAS
mItemDao.insert(new Item(2,"Item2")); //<<<<<<<<<< AS WAS
logItemInfo(mItemDao.getItemById(1)); //<<<<<<<<<< AS WAS
logItemInfo(mItemDao.getItemById(2)); //<<<<<<<<<< AS WAS
logItemInfo(mItemDao.getItemById(100)); //<<<<<<<<<< ATTEMPT TO GET AN INVALID ID
导致空指针异常(尝试访问logItemInfo方法中的Item时),因为没有 id为100的Item ,这可能是导致此问题的原因您已经描述了(即,您正在请求不存在的行)。
将 logItemInfo 方法修改为:-
private void logItemInfo(Item i) {
if (i == null) {
Log.d("ITEMINFO","NOT AN ITEM");
return;
}
Log.d("ITEMINFO","Item is " + i.getIName() + " ID is " + i.getIId());
}
结果输出(而不是异常)是:-
2019-10-02 07:57:21.189 11388-11388/aso.asofkinroom D/ITEMINFO: Item is Item1 ID is 1
2019-10-02 07:57:21.190 11388-11388/aso.asofkinroom D/ITEMINFO: Item is Item2 ID is 2
2019-10-02 07:57:21.190 11388-11388/aso.asofkinroom D/ITEMINFO: NOT AN ITEM