简体   繁体   中英

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() .

I have this structure in my Firebase:

Questions

--> list_of_documents wUniqueIDs

--->fields in documents:

+ question

+ answer

+ rating

so far i have this under 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.

I've been trying to follow tutorials and looking at other posts on stackOverflow but none seem to address this.

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 ---------

@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 . Please also note that there is no way in Java in which you can cast an CollectionReference object to a Task. So to solve this, just remove the declaration of your collectionReference object like this:

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. To be able to update a specific document, you need to pass the actual id of document so it can be updated:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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