我目前已经创建了一种使用Firestore更新图书的方法。我试图在onOptionsItemSelected中调用此方法。
我对Android比较陌生,在调用这个方法时我总是把它称为updateBook(Book book)。
下面是我的updateBook方法
@Override
public void updateBook(Book book) {
String chapterName = editTextChapterName.getText().toString().trim();
String chapterInfo = editTextChapterInfo.getText().toString().trim();
int chapterNumber = numberPickerChapterNumber.getValue();
if (chapterName.trim().isEmpty() || chapterInfo.trim().isEmpty()) { //ensure that user has not left boxes empty
Toast.makeText(this, "Please add a chapter name and the chapter information", Toast.LENGTH_SHORT).show();
}
FirebaseFirestore db = FirebaseFirestore.getInstance();
DocumentReference bookRef = db.collection("Book")
.document();
bookRef.update("chapterName", book.getChapterName(),
"chapterInfo", book.getChapterInfo(),"chapterNumber", book.getChapterNumber())
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()){
Toast.makeText(AdminUpdateActivity.this, "Success", Toast.LENGTH_SHORT).show();
}
}
});
下面是我试图调用我的方法的地方
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.save_icon:
updateBook();
return true;
default:
return super.onOptionsItemSelected(item);
}
在updateBook括号内我收到错误“无法应用于()”。
我已经阅读了有关此主题的其他问题但尚未找到解决方案。有人可以解释如何解决这个问题,为什么?
谢谢
要解决此问题,您应该更改以下代码行:
DocumentReference bookRef = db.collection("Book")
.document();
至
DocumentReference bookRef = db.collection("Book")
.document(bookId);
如果不将书的ID传递给document()
方法,Firebase SDK并不真正知道您要更新哪个书籍对象。除此之外,在document()
上调用DocumentReference
方法它每次只生成一个新的随机id。
还需要另一个变化。还请从updateBook()
方法中删除参数。应该:
public void updateBook() {}
没有任何争论。