首页 > 解决方案 > Error when trying to call method - Cannot be applied to ()

问题描述

Image of DB structure

I have currently created a method for updating a book using Firestore. I am attempting to call this method in onOptionsItemSelected.

I am relatively new to Android and was always under the impression when calling this method I would call it as updateBook(Book book).

Below is my updateBook method

@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();
                    }

                }
            });

Below is where I am trying to call my method

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.save_icon:
            updateBook();
        return true;
        default:
            return super.onOptionsItemSelected(item);
    }

Within the updateBook parenthesis I am getting an error "Cannot be applied to ()".

I have read through other questions on here to do with this topic but have not found a solution. Can someone explain how to fix this issue and why?

Thanks

标签: javaandroidfirebasegoogle-cloud-firestore

解决方案


要解决此问题,您应该更改以下代码行:

DocumentReference bookRef = db.collection("Book")
        .document();

DocumentReference bookRef = db.collection("Book")
        .document(bookId);

如果不将书籍的 id 传递给document()方法,Firebase SDK 并不真正知道您要更新哪个书籍对象。除此之外,在它上调用document()方法DocumentReference每次只生成一个新的随机 id。

还需要进行另一项更改。updateBook()还请从您的方法中删除参数。应该:

public void updateBook() {}

没有任何争论。


推荐阅读