How can i send data from Activity to Fragment using LiveData and ViewModel class
Asked Answered
C

1

9

Now today, LiveData is very popular, How can i send data from activity to fragment using ViewModel and LiveData or vice-versa ? Please explain with coding example.

Calle answered 22/9, 2018 at 16:33 Comment(1)
have a look at this ... medium.com/@taman.neupane/…Endoskeleton
O
10

In Activity

public class MyActivity extends AppCompatActivity {

    MyViewModel myViewModel;
    Handler handler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_activity);
        handler = new Handler();
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.container, MyFragment.newInstance())
                    .commitNow();
        }
        //Make View Holder Object
        myViewModel=ViewModelProviders.of(this).get(MyViewModel.class);
        myViewModel.init();
        myViewModel.sendData("Hello kamy");

        // Make thread to send data again
        new Thread(new Runnable() {
            @Override
            public void run() {
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            myViewModel.sendData("How are You ?");
                        }
                    });

            }
        }).start();
    }
}

In ViewModel Class

public class MyViewModel extends ViewModel {
    // TODO: Implement the ViewModel
    private MutableLiveData<String> stringMutableLiveData;

    public void init()
    {
        stringMutableLiveData=new MutableLiveData<>();

    }

    public void sendData(String msg)
    {
        stringMutableLiveData.setValue(msg);
    }

    public LiveData<String> getMessage()
    {
        return stringMutableLiveData;


    }
}

In Fragment

public class MyFragment extends Fragment {

    private MyViewModel mViewModel;
    private TextView textView;

    public static MyFragment newInstance() {
        return new MyFragment();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view= inflater.inflate(R.layout.my_fragment, container, false);
        textView=(TextView)view.findViewById(R.id.message);

        return  view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = ViewModelProviders.of(this).get(MyViewModel.class);
        ViewModelProviders.of(getActivity()).get(MyViewModel.class).getMessage().observe(this, new Observer<String>() {
            @Override
            public void onChanged(@Nullable String message) {
                textView.setText(message);
                Toast.makeText(getContext(),message,Toast.LENGTH_SHORT).show();

            }
        });
    }

}

fragment xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/my"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.my.MyFragment">

    <TextView
        android:id="@+id/message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="MyFragment"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
Olindaolinde answered 22/9, 2018 at 16:38 Comment(2)
Thanks for explain me :) its really helpful me any link of this projectCalle
yes sure clone this project github.com/kamydeep00178/ActivityToFragOlindaolinde

© 2022 - 2024 — McMap. All rights reserved.