Michael
Michael

Reputation: 439

How to make fragment A know that button in fragment B is pressed

a bit complex but I'll try to explain. I have 3 fragments. First Fragment (NoteFragment) holds the recycler view of all notes. Second Fragment (AddNoteFragment) opens when I click the Add Note button, which is this button in the first Fragment. A third fragment (RemoveNoteFragment) is a fragment that appears after I click on one of the notes. (I have a listener in the NoteAdapter).

First fragment and second fragment appear in the same frame layout. In a second fragment I have a button that as soon as I click it I want to delete the note (from recycler view and firebase - see the code how i do it).

Note Fragment

public class NoteFragment extends Fragment implements View.OnClickListener {

    private RecyclerView RVNotesList;
    private ArrayList<Note> notes = new ArrayList<>();
    private NotesAdapter adapter;
    private ImageView mAddNoteBTN;
    private Note note;
    private ArrayList<String> keys = new ArrayList<>();

    private FirebaseAuth mAuth;
    private FirebaseDatabase db;
    private DatabaseReference users;
    private RecyclerView.LayoutManager layoutManager;

    private Fragment removeFragment;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main_notes, container, false);
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        removeFragment = new RemoveNoteFragment();
        mAuth = FirebaseAuth.getInstance();
        db = FirebaseDatabase.getInstance();
        users = db.getReference("Users").child(mAuth.getCurrentUser().getUid()).child("Notes");
        mAddNoteBTN = view.findViewById(R.id.addNoteBTN);
        mAddNoteBTN.setOnClickListener(this);
        RVNotesList = view.findViewById(R.id.RVNotesList);
        users.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull final DataSnapshot dataSnapshot) {

                notes.clear();
                for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
                    note = dataSnapshot1.getValue(Note.class);
                    notes.add(note);
                    keys.add(dataSnapshot1.getKey());
                }
                adapter = new NotesAdapter(notes, getActivity(), keys);
                if (adapter.getItemCount() <= 3) {
                    layoutManager = new GridLayoutManager(getActivity(), 1);
                } else {
                    layoutManager = new GridLayoutManager(getActivity(), 3);
                }
                RVNotesList.setLayoutManager(layoutManager);
                RVNotesList.setAdapter(adapter);
                adapter.setOnNoteClickListener(new NotesAdapter.OnNoteClickListener() {
                    @Override
                    public void onNoteClick(final int position) {
                        getFragmentManager().beginTransaction().replace(R.id.bottom_container, removeFragment)
                                .commit();
                        String key = keys.get(position);
                        users.child(key).removeValue();
                    }
                });
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
        return view;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.addNoteBTN:
                getFragmentManager().beginTransaction().setCustomAnimations(R.anim.enter_left_to_right, R.anim.exit_left_to_right).replace(R.id.bottom_container, new AddNoteFragment())
                        .commit();
                break;
        }
    }
}

Add Note Fragment

public class AddNoteFragment extends Fragment implements View.OnClickListener, AddNotePresenter {

    private EditText ETnoteTitle, ETnoteDesc;
    private TextView TVnoteLastDate;
    private Button saveNoteBTN, deleteNoteBTN, BTNtaskDatePicker;
    private Note note;

    private int day;
    private int month;
    private int year;

    private Calendar c;
    private DatePickerDialog dpd;

    private AddNoteView addNoteView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_add_note, container, false);

        addNoteView = new AddNoteView(this);
        ETnoteTitle = view.findViewById(R.id.noteTitle);
        ETnoteDesc = view.findViewById(R.id.noteDesc);
        TVnoteLastDate = view.findViewById(R.id.TVnoteLastDate);
        BTNtaskDatePicker = view.findViewById(R.id.taskDatePicker);
        BTNtaskDatePicker.setOnClickListener(this);
        saveNoteBTN = view.findViewById(R.id.saveNoteBTN);
        saveNoteBTN.setOnClickListener(this);
        deleteNoteBTN = view.findViewById(R.id.deleteNoteBTN);
        deleteNoteBTN.setOnClickListener(this);
        return view;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.saveNoteBTN:
                saveNote();
                hideKeyboard(getActivity());
                break;
            case R.id.deleteNoteBTN:
                removeAddNoteFragment();
                hideKeyboard(getActivity());
                break;
            case R.id.taskDatePicker:
                showDatePicker();
                break;
        }
    }

    @Override
    public void removeAddNoteFragment() {
        getFragmentManager().beginTransaction().
                remove(getFragmentManager().findFragmentById(R.id.bottom_container)).commit();
    }

    public void showDatePicker() {
        c = Calendar.getInstance();
        day = c.get(Calendar.DAY_OF_MONTH);
        month = c.get(Calendar.MONTH);
        year = c.get(Calendar.YEAR);

        dpd = new DatePickerDialog(getActivity(), R.style.DialogTheme, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int mYear, int mMonth, int mDay) {
                day = mDay;
                month = mMonth + 1;
                year = mYear;
                TVnoteLastDate.setText(mDay + "/" + (mMonth + 1) + "/" + mYear);
            }
        }, day, month, year);
        dpd.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
        dpd.show();
    }

    public void saveNote() {
        String title = ETnoteTitle.getText().toString().trim();
        String desc = ETnoteDesc.getText().toString().trim();
        String date = TVnoteLastDate.getText().toString().trim();
        if (title.isEmpty() || desc.isEmpty() || date.isEmpty()) {
            return;
        }
        note = new Note(title, desc, day, month, year);
        addNoteView.pushNote(note);
    }

    public static void hideKeyboard(Activity activity) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
        View view = activity.getCurrentFocus();
        if (view == null) {
            view = new View(activity);
        }
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
}

Remove Note Fragment

public class RemoveNoteFragment extends Fragment{

    private ImageView IVremoveNote;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_remove_note, container, false);
        IVremoveNote = view.findViewById(R.id.IVremoveNote);

        return view;
    }

}

Note Adapter

public class NotesAdapter extends RecyclerView.Adapter<NotesAdapter.NotesViewHolder> {

    private ArrayList<Note> notes;
    private Context context;
    private ArrayList<String> keys;
    private OnNoteClickListener onNoteClickListener;

    public NotesAdapter(ArrayList<Note> notes, Context context, ArrayList<String> k) {
        this.notes = notes;
        this.context = context;
        this.keys = k;
    }

    public interface OnNoteClickListener {
        void onNoteClick(int position);
    }

    public void setOnNoteClickListener(OnNoteClickListener onNoteClickListener) {
        this.onNoteClickListener = onNoteClickListener;
    }

    @NonNull
    @Override
    public NotesViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.note_list_item, parent, false);
        return new NotesAdapter.NotesViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull final NotesViewHolder holder, final int position) {
        final Note note = notes.get(position);
        holder.TVnoteCardTitle.setText(notes.get(position).getmNoteTitle());
        holder.TVnoteCardDesc.setText(notes.get(position).getmNoteDescription());
        String lastDayToConfirmNote = (notes.get(position).getmDay() + "/"
                + notes.get(position).getmMonth() + "/" + notes.get(position).getmYear());
        holder.TVnoteCardLastDate.setText(lastDayToConfirmNote);

    }

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

    public class NotesViewHolder extends RecyclerView.ViewHolder {

        private TextView TVnoteCardTitle;
        private TextView TVnoteCardDesc;
        private TextView TVnoteCardLastDate;


        public NotesViewHolder(@NonNull View itemView) {
            super(itemView);
            TVnoteCardTitle = itemView.findViewById(R.id.TVnoteCardTitle);
            TVnoteCardDesc = itemView.findViewById(R.id.TVnoteCardDesc);
            TVnoteCardLastDate = itemView.findViewById(R.id.TVnoteCardLastDate);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (onNoteClickListener != null) {
                        onNoteClickListener.onNoteClick(getAdapterPosition());
                    }
                }
            });
        }
    }
}

what do I want ? I want that once I click on the IVremoveNote that is inside the RemoveNoteFragment, my NoteFragment knows this, and I can do the actions within it (in NoteFragment) .

Or if you have another solution for deleting a note, I'd love to hear.

Notice that for deleting the note, I use the listener inside the note adapter, which accepts the keys array list position.

Upvotes: 1

Views: 73

Answers (3)

nulldroid
nulldroid

Reputation: 1230

You should really think about using LiveData and ViewModel from the Architecture components for your purpose, which is a recommended design pattern by Google. It needs a bit of time to get the hang of it, but you can use it for almost every app and it will make your problem really easy. See the following overview for example. Here is a very good YouTube tutorial that describes exactly your note example, not for Firebase but for Android Room (local db instead of cloud). Its a bit lengthy but you will have a good understanding afterwards.

Basically from your Firebase db you query all notes to receive a LiveData> allNotes

You can then observe the LiveData allNotes to get the list and set it to your RecyclerView. This way, you will always have up-to-date data in your recyclerview. When you delete a note from the db, it will automatically update the list and show it in recyclerview.

Upvotes: 0

Ruthwik Warrier
Ruthwik Warrier

Reputation: 197

Hope these fragments are hosted by the same activity. You can call an activity's method from a fragment by ((YourActivityClassName)getActivity()).yourPublicMethod();

There you can write your logic to call the fragments method, listener or whatever

Upvotes: 0

Rishabh Sharma
Rishabh Sharma

Reputation: 179

One thing you can do is to make a method in NoteFragment and then call the method when IVremoveNote in RemoveNoteFragment is pressed. In this method, you can add the functionality to remove the node/row. Tip! - you can pass the note/row information in the method argument. I hope it helps.

Upvotes: 1

Related Questions