1

При нажатии на какую либо "заметку" в RecyclerView в первом фрагменте, нужно передать эту "заметку" в другой фрагмент, где можно будут её отредактировать. При моем коде во втором фрагменте в bundle приходит null. Прошу, помогите.

Слушатель нажатий в первом фрагменте:

adapter.setOnNoteClickListener(new NotesAdapter.OnNoteClickListener() {
    @Override
    public void onNoteClick(Note note) {
        presenter.onNoteClicked(note);
        Navigation.findNavController(view).navigate(R.id.dest_create_note);
        }
    });

Код метода вызываемого в слушателе первого фрагмента:

@Override
public void onNoteClicked(Note note) {
    CreateNoteFragment fragment = new CreateNoteFragment();
    Bundle bundle = new Bundle();
    bundle.putParcelable("Note", note);
    fragment.setArguments(bundle);
}

Код на получение и установку полученных данных объекта во втором фрагменте:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
    setHasOptionsMenu(true);
    Bundle bundle = this.getArguments();
    if (bundle != null) {
        note = bundle.getParcelable("Note");
    }
    if (note != null) {
        editTextTitle.setText(note.getTitle());
        editTextDescription.setText(note.getDescription());
            textViewDate.setText(String.format(getResources().getString(R.string.date_of_update), presenter.date()));
    }
    return inflater.inflate(R.layout.fragment_create_note, container, false);
}

Реализация Parcelable в Model:

@Entity(tableName = "notes")
public class Note implements Parcelable {

    @PrimaryKey(autoGenerate = true)
    private int id;
    private String title;
    private String description;
    private String date;

    public Note(String title, String description, String date) {
        this.title = title;
        this.description = description;
        this.date = date;
    }

    @Ignore
    public Note ()  {
    }

    protected Note(Parcel in) {
        this.id = in.readInt();
        this.title = in.readString();
        this.description = in.readString();
        this.date = in.readString();
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(this.id);
        dest.writeString(this.title);
        dest.writeString(this.description);
        dest.writeString(this.date);
    }

    @Override
    public int describeContents() {
        return 0;
    }

    public static final Creator<Note> CREATOR = new Creator<Note>() {
        @Override
        public Note createFromParcel(Parcel in) {
            return new Note(in);
        }

        @Override
        public Note[] newArray(int size) {
            return new Note[size];
        }
    };

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }
}

1 ответ 1

2

Насколько я понял ваш код - вы используете NavigationComponents. Механика создания фрагментов в нем отличается от стандартной.

Если вы посмотрите на метод Navigation.findNavController(view).navigate(); то увидите следующее.

/**
     * Navigate to a destination from the current navigation graph. This supports both navigating
     * via an {@link NavDestination#getAction(int) action} and directly navigating to a destination.
     *
     * @param resId an {@link NavDestination#getAction(int) action} id or a destination id to
     *              navigate to
     * @param args arguments to pass to the destination
     */
    public void navigate(@IdRes int resId, @Nullable Bundle args) {
        navigate(resId, args, null);
    }

Соответственно если вы хотите передать какие-то аргументы в создаваемый фрагмент вам необходимо создавать свой Bundle и класть его вторым параметром в метод navigate().

Bundle bundle = new Bundle()
bundle.putParcelable(ARG_NOTE, note)
Navigation.findNavController(view).navigate(resId, bundle)

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.