0

I am using Parcelable when I am sending data between fragments. I send my object class from 'TasksFragment' to 'EditTaskFragment'. My object class is below.

public class TaskResult extends BaseObservable implements Parcelable {

private int taskID;
private String taskName;

public TaskResult() {
}

public int getTaskID() {
    return taskID;
}

public void setTaskID(int taskID) {
    this.taskID = taskID;
}

@Bindable
public String getTaskName() {
    return taskName;
}

public void setTaskName(String taskName) {
    this.taskName = taskName;
    notifyPropertyChanged(BR.taskName);
}

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

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeInt(this.taskID);
    dest.writeString(this.taskName);
}

protected TaskResult(Parcel in) {
    this.taskID = in.readInt();
    this.taskName = in.readString();
}


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

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

}

I get the data like this in 'EditTaskFragment';

 mViewModel.taskResult = 
   getArguments().getParcelable(Keys.KEY_TASK_RESULT);

For example when I updated an any data in TaskResult class which I get, the data which in TasksFragment updated, too.

This value updated in TasksFragment, too. But I don't it. How do I?

If I clone this class, is it mind?

Barış Sağlam
  • 61
  • 2
  • 11
  • `mViewModel.taskResult = ` serious question: are you aware what you're doing here? You're passing a parcelable ("complex") data into a ViewModel from Fragment A to Fragment B through intents... I don't think you understand how ViewModels work... As such I recommend reading about it here: https://developer.android.com/topic/libraries/architecture/viewmodel – Zun Aug 13 '19 at 10:52
  • See the section "Share data between fragments". Don't guess code. Just copy and paste from the **OFFICIAL GUIDES** and adjust to your requirements – Zun Aug 13 '19 at 10:54

1 Answers1

2

Why do you send your data by the fragment arguments when you are using the viewmodel? The viewmodel is the best solution to share any data between the multiple fragments.

By anyway, I assume that you use the viewmodel in both fragments based on the one activity. Reason of your problem is that the instance of the viewmodel is equal in your fragments.

No Body
  • 671
  • 5
  • 14
  • Why do you persist to use the viewmodel in this way? When an object is shared between two fragments and you are using the viewmodel, putting the shared element in the viewmodel is the best practise. – No Body Aug 13 '19 at 12:28