Ashish
Ashish

Reputation: 6919

Get Data in Fragment through Retrofit

In this problem I want to get Data from My API

In which I get Data from Retrofit

I want to show data in RecyclerView in Fragment Tabs but how can I send data from activity to Fragment

This is all I have tried

Retrofit call which provide me ArrayList of my posts

getMainApp().swiftAPI.getPosts().enqueue(object : Callback<ArrayList<Post>>{
            override fun onFailure(call: Call<ArrayList<Post>>?, t: Throwable?) {
                Toast.makeText(this@DashboardActivity, t?.message, Toast.LENGTH_SHORT)
            }

            override fun onResponse(call: Call<ArrayList<Post>>?, response: Response<ArrayList<Post>>?) {
                if (response?.isSuccessful!!){

                }
            }

PagesFragment

val rootView = inflater.inflate(R.layout.fragment_page, container, false)
        val video_recyclerview = rootView.findViewById(R.id.pages_rcv) as RecyclerView // Add this
        video_recyclerview.layoutManager = LinearLayoutManager(activity)
        video_recyclerview.adapter = PagesAdapter()
        return rootView

I want to Know if there is any way possible to send ArrayList to fragment cause my data is in ArrayList As shown in Picture

Upvotes: 2

Views: 6428

Answers (3)

Nicola Gallazzi
Nicola Gallazzi

Reputation: 8713

You can define an interface in your activity and let the fragment implement the interface. You can follow this example on my github: ActivityToFragmentCommunication

Basically, in your activity define:

  public interface DataLoadedListener {
        public void onDataLoaded(ArrayList<Post> posts);
    }

Then, make your fragment implement the interface like below:

public class ExampleFragment extends Fragment implements MainActivity.DataLoadedListener {

  // your fragment code
}

Finally in the onCreate() method of your activity:

// Create new fragment and transaction
        mExampleFragment = new ExampleFragment();
        // setting mExampleFragment as data load listener
        mDataLoadedListener = (DataLoadedListener) mExampleFragment;
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        // Replace whatever is in the fragment_container view with this fragment,
        // and add the transaction to the back stack if needed
        transaction.replace(R.id.flContainer, mExampleFragment);
        transaction.addToBackStack(null);
        // Commit the transaction
        transaction.commit();

        // load data after click
        btLoadData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                loadData();
                // notify attached fragment
                mDataLoadedListener.onDataLoaded(myStrings);
            }
        });

Upvotes: 4

Bram Sinke
Bram Sinke

Reputation: 193

Since you are working on Android, I would recommend the ViewModel component which makes it really easy to communicate between a activity and it's fragments.

First add the package to your app

    implementation 'androidx.lifecycle:lifecycle-extensions:2.0.0'

Then create a ViewModel class

public class MyViewModel extends ViewModel {
    public MutableLiveData<ArrayList<Post>> posts = new MutableLiveData<ArrayList<Post>>();
}

Now in the fragment subscribe to it.

 public class DetailFragment extends Fragment {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SharedViewModel model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
        model.posts.observe(this, { posts ->
           // Update the UI.
        });
    }
 }

Then set the value in your MainActivity as shown below and voila you have the data in your fragment. You can read more about it here

public class MyActivity extends AppCompatActivity {
    public void onCreate(Bundle savedInstanceState) {
        // Create a ViewModel the first time the system calls an activity's onCreate() method.
        // Re-created activities receive the same MyViewModel instance created by the first activity.

        MyViewModel model = ViewModelProviders.of(this).get(MyViewModel.class);
        model.users.setValue(posts);
    }
}

Upvotes: 0

Tariqul Islam
Tariqul Islam

Reputation: 704

First check currentFragment in your activity class. You will get the fragment reference object in your activity class . so the example will like below:

Suppose you have a fragment called DataFragment and you have a reference mDataFragment in your activity class. now when you get data in your activity class you will call ((DataFragment)mDataFragment).passData(yourDataList). Remember passData() is a public method in your fragment class. Then you can add data in adapter and call notifyDataSetChanged()

Upvotes: 0

Related Questions