更新Fire-store文档后,后退按钮可重新打开活动

时间:2019-03-04 04:52:52

标签: android database firebase android-activity google-cloud-firestore

我的功能听起来很简单。

我有一个recycler-view,其中有一堆文档作为名片视图。当我单击一个元素时,将打开一个新活动,并向我显示文档的详细信息,例如标题,内容等。它们放置在TextInputEditText上,因此可以编辑。用户进行更改并单击“后退”按钮后,需要更新文档。听起来很简单吧?但是这里的问题是,当我按下“后退”按钮时,活动再次重新打开。虽然该文档仍被更新。

这是我的NoteListAdapter.java代码,它为onClick元素实现了recycler-view侦听器。

package com.seeme.Adapters;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.snackbar.Snackbar;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.QuerySnapshot;
import com.seeme.FirstScreen;
import com.seeme.Model.Note;
import com.seeme.R;
import com.seeme.UpdateNoteActivity;

import org.w3c.dom.Text;

import java.util.List;
import java.util.Random;

import javax.annotation.Nullable;

public class NoteListAdapter extends RecyclerView.Adapter<NoteListAdapter.ViewHolder> {

    private Context context;

    public List<Note> notes;
    private static String TAG = "NoteListAdapter LOG : ";
    private FirebaseFirestore mFirestore;
    private FirebaseAuth mAuth;
    private FirebaseUser mUser;

    public String docID;

    public NoteListAdapter(List<Note> note) {

        this.notes=note;


    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.note_item, parent, false);
        mFirestore = FirebaseFirestore.getInstance();
        mAuth = FirebaseAuth.getInstance();
        mUser = mAuth.getCurrentUser();

        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.title_item.setText(notes.get(position).getTitle());
        holder.content_item.setText(notes.get(position).getContent());

        holder.cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "onClick: OnBindViewHolder + position : " + position);
                retrieveDocid(position);


            }
        });





    }

    private void retrieveDocid(int itemposition) {

        mFirestore.collection("users").document(mUser.getUid()).collection("notes").addSnapshotListener(new EventListener<QuerySnapshot>() {
            @Override
            public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) {
                if (e!=null) {
                    Log.e(TAG, "onEvent: ", e );
                }
                else {

                    docID = queryDocumentSnapshots.getDocuments().get(itemposition).getId();
                    Log.d(TAG, "onEvent: DOC ID  = " + docID);

                    Intent intent;
                    intent = new Intent(context, UpdateNoteActivity.class);
                    intent.putExtra("id", docID);
                    context.startActivity(intent);                }
            }


        });
    }

    @Override
    public int getItemCount() {
        return notes.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        View mView;

        public TextView title_item;
        public TextView content_item;
        public CardView cardView;


        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            mView = itemView;
            context = itemView.getContext();

            title_item = itemView.findViewById(R.id.item_title);
            content_item = itemView.findViewById(R.id.item_content);
            cardView = itemView.findViewById(R.id.noteItem_card);

        }
    }


}

UpdateNoteActivity.java更新文档的值。但是就像我说的那样,当我按下后退按钮时,活动将重新打开。反正要解决这个问题吗?

package com.seeme;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.textfield.TextInputEditText;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;

import java.util.HashMap;

import javax.annotation.Nullable;

import butterknife.BindView;
import butterknife.ButterKnife;

public class UpdateNoteActivity extends AppCompatActivity {

    @BindView(R.id.content_editText)
    TextInputEditText content_editText;
    @BindView(R.id.capture_btn)
    FloatingActionButton captureBtn;
    @BindView(R.id.title_edittext)
    TextInputEditText titleEdittext;
    private FirebaseFirestore mFirestore;
    private FirebaseAuth mAuth;
    private FirebaseUser mUser;

    public String documentID;

    public static String TAG = "UpdateNoteActivity : ";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update_note);
        ButterKnife.bind(this);

        documentID = getIntent().getStringExtra("id");

        mFirestore = FirebaseFirestore.getInstance();
        mAuth = FirebaseAuth.getInstance();
        mUser = mAuth.getCurrentUser();


        Toast.makeText(this, "" + documentID, Toast.LENGTH_SHORT).show();

        getDocDetails(documentID);
    }

    @Override
    public void onBackPressed() {

       // updateNote();
        super.onBackPressed();
     }

    @Override
    protected void onPause() {
        Toast.makeText(this, "PAUSED", Toast.LENGTH_SHORT).show();
        updateNote();
        super.onPause();
    }

    private void updateNote() {

        String string_title = titleEdittext.getText().toString();
        String string_content = content_editText.getText().toString();

        HashMap<String, Object> updateHash = new HashMap<>();
        updateHash.put("title", string_title);
        updateHash.put("content", string_content);

        mFirestore.collection("users").document(mUser.getUid()).collection("notes").document(documentID).update(updateHash)
                .addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        Toast.makeText(UpdateNoteActivity.this, "UPDATED!", Toast.LENGTH_SHORT).show();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Log.e(TAG, "onFailure: Update func ERROR", e );
                    }
                });

    }

    private void getDocDetails(String docID) {
        mFirestore.collection("users").document(mUser.getUid()).collection("notes").document(docID).addSnapshotListener(new EventListener<DocumentSnapshot>() {
            @Override
            public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {
                if (e != null) {
                    Log.e(TAG, "onEvent: ", e);
                } else {
                    String docTitle = documentSnapshot.get("title").toString();
                    String docContent = documentSnapshot.get("content").toString();

                    content_editText.setText(docContent);
                    titleEdittext.setText(docTitle);
                    Log.d(TAG, "onEvent: Document title = " + docTitle + "\n Document Content = " + docContent);


                }
            }
        });
    }
}

1 个答案:

答案 0 :(得分:0)

onBackPressed从缓存重新打开活动。如果要更新recyclerview数据,则应重新创建您的recycler活动。单击UpdateNoteActivity.java中的“后退”按钮后,可以使用它来重新创建回收者活动

 @Override
public void onBackPressed() {

   // Open your list activity with FLAG_ACTIVITY_CLEAR_TOP flag
   Intent mIntent = new Intent(UpdateNoteActivity.this, NoteListActivity.class); 
   mIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
   startActivity(mIntent);
   super.onBackPressed();
 }

第二种方法是从“回收商列表”活动中调用startActivityForResult,并在成功更新记录调用setResult()后使用更新后的值,并在onActivityResult()的回收商活动中处理该值,并更新您的回收商列表。