简体   繁体   English

如何在Firestore RecyclerView中更新项目?

[英]How to update an item in Firestore RecyclerView?

I am trying to update an item in my RecyclerView with a save button in the toolbar which calls updateQuestion() . 我正在尝试使用工具栏上的保存按钮updateQuestion()调用updateQuestion()更新RecyclerView的项目。

I have this structure in my Firebase: 我的Firebase中具有以下结构:

Questions

--> list_of_documents wUniqueIDs -> list_of_documents wUniqueIDs

--->fields in documents: --->文档中的字段:

+ question + question

+ answer + answer

+ rating + rating

so far i have this under updateQuestion() 到目前为止,我在updateQuestion()下拥有此updateQuestion()

private void updateQuestion() {
        String questionString = mQuestionTextView.getText().toString();
        Object updatedText = mQuestionEditText.getText().toString();
        String questionPath2 = rootRef.collection("Questions").document().getPath();

        FirebaseFirestore rootRef = FirebaseFirestore.getInstance();

        CollectionReference collectionReference = rootRef.collection(questionPath2).document().update("question", updatedText); // <--- I GET ERROR HERE
}
error: incompatible types: Task<Void> cannot be converted to CollectionReference

I also got an error previously saying that the second parameter for update() needs to be an object however this error has seemed to disappear. 我也收到一个错误,之前说的是update()的第二个参数需要是一个对象,但是这个错误似乎已经消失了。

I've been trying to follow tutorials and looking at other posts on stackOverflow but none seem to address this. 我一直在尝试遵循教程,并在stackOverflow上查看其他文章,但似乎都没有解决这个问题。

Here is what i've tried previously: 这是我以前尝试过的:

//        CollectionReference ref = rootRef.collection("Questions").document().collection("question");
//        CollectionReference ref = rootRef.collection("Questions").document().collection(questionPath);

//        Toast.makeText(this, "this is the path: " + questionPath, Toast.LENGTH_SHORT).show();
//        Log.d(TAG, "updateQuestion: " + ref.get(question.getAnswer));
//        Log.d(TAG, "updateQuestion: " + ref.collection(questionPath).document("question", questionPath).toString())
//        Log.d(TAG, "updateQuestion: " + ref.document(questionPath)("question").toString());
//        Log.d(TAG, "updateQuestion: " + ref.document(questionPath).get(question).toString());
//        ref.collection("question")
//        db.child("Spacecraft").push().setValue(spacecraft);
//        rootRef.collection("Questions").document().update("question", updatedText);
//        rootRef.collection("Questions").document(questionPath).update("question", updatedText);

//        TextView savedText = mQuestionTextView.setText(updatedText);

//        DocumentReference documentReference = rootRef.collection("Questions").document(questionPath).update("question", );
//        DocumentReference documentReference = rootRef.document(questionPath).update("question", updatedText);
//        CollectionReference collectionReference = rootRef.collection(questionPath).document().update("question", updatedText);

Any and all help is appreciated. 任何和所有帮助表示赞赏。

------------------ Revised Code as of 2019 - 04 - 07 @ 1153pm --------- ------------------ 修订版代码截至2019年4月7日@ 1153pm ---------

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {

            case R.id.save_question:
                mShowSaveIcon = false;
                updateQuestion();
                break;

            case R.id.edit_question:
                item.setVisible(false);
                enableEditMode();
                mShowSaveIcon = true;
                break;

        }
        invalidateOptionsMenu();
        return true;
    }

    private void enableEditMode(){

        mQuestionEditText = findViewById(R.id.questionEditTextID);
        mPostAnswerButton.setEnabled(false);
        mPostAnswerButton.setBackgroundColor(getResources().getColor(android.R.color.darker_gray));

        mCommentButton.setEnabled(false);
        mCommentButton.setBackgroundColor(getResources().getColor(android.R.color.darker_gray));

        String questionString = mQuestionTextView.getText().toString();
        mQuestionTextView.setVisibility(View.GONE);
        mQuestionEditText.setVisibility(View.VISIBLE);
        mQuestionEditText.setText(questionString);
    }



    private void updateQuestion(){
        Question question = createQuestionObj();
        updateQuestionToCollection(question);
    }

    private Question createQuestionObj(){
        final Question question = new Question();
        return question;
    };

private void updateQuestionToCollection(Question question) {
        String questionString = mQuestionTextView.getText().toString();
        Object updatedText = mQuestionEditText.getText().toString();


        FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
        String docId = rootRef.collection("Questions").document().getId();
        System.out.println(docId);
        String questionPath = rootRef.collection("Questions").document(docId).collection("question").getPath();
//        String questionPath2 = rootRef.collection("Questions").document(docId).getPath();

        System.out.println(questionPath);
        rootRef.collection(questionPath).document(docId).update("question", updatedText).addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                Log.d(TAG, "onSuccess: it worked");
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.d(TAG, "onFailure: it failed because of: " + e.toString());
            }
        });

finish();
 }
};

DataBase Structure Snippet Below 下面的数据库结构片段

在此处输入图片说明

When I'm looking at your code I see two problems. 当我查看您的代码时,我看到两个问题。 The first one is the following error: 第一个是以下错误:

error: incompatible types: Task<Void> cannot be converted to CollectionReference

Which is produced because when you are calling update() method on a DocumentReference object, the object that is returned is of type Task<Void> and not CollectionReference . 之所以产生这种情况是因为,当您在DocumentReference对象上调用update()方法时,返回的对象的类型为Task<Void>不是 CollectionReference Please also note that there is no way in Java in which you can cast an CollectionReference object to a Task. 另请注意,Java中无法将CollectionReference对象强制转换为Task。 So to solve this, just remove the declaration of your collectionReference object like this: 因此,要解决此问题,只需删除您的collectionReference对象的声明,如下所示:

rootRef.collection(questionPath2).document("specificDocId").update("question", updatedText);

The second issue is that you are generating a new document id each time you are calling updateQuestion() since you aren't passing any id to the document() method. 第二个问题是,每次调用updateQuestion()时都会生成一个新的文档ID,因为您没有将任何ID传递给document()方法。 To be able to update a specific document, you need to pass the actual id of document so it can be updated: 为了能够更新特定的文档,您需要传递文档的实际ID,以便可以对其进行更新:

rootRef.collection(questionPath2).document("specificDocId").update("question", updatedText);

Edit: 编辑:

In order to update a document use this reference: 为了更新文档,请使用以下参考:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference questionsRef = rootRef.collection("questions");
DocumentReference docRef = questionsRef.document("yCCRgoRIAmtmKmTFLYJX");
docRef.update("question", updatedText);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM