I'm using an Interface to send a list of objects from an activity to a fragment. here is my Interface :
public interface CurrenciesSync {
void syncCurrencies(List<CurrencyModel> currencies);
}
Here is the way I call interface method to set data :
public void getCurrencies(){
APIInterface apiInterface = APIClient.getClient().create(APIInterface.class);
Call<GetCurrenciesModel> call = apiInterface.getCurrencies();
call.enqueue(new Callback<GetCurrenciesModel>() {
@Override
public void onResponse(Call<GetCurrenciesModel> call, Response<GetCurrenciesModel> response) {
if(response.isSuccessful()) {
if (response.body().getStatus() == true){
currencies = new ArrayList<CurrencyModel>();
for (int i = 0 ; i< response.body().getCurrencies().size(); i++){
currencies.add(response.body().getCurrencies().get(i));
}
new FeesFragment();
CurrenciesSync currenciesSync = new CurrenciesSync() {
@Override
public void syncCurrencies(List<CurrencyModel> currencies) {
// your code
}
};
currenciesSync.syncCurrencies(currencies);
}
}
@Override
public void onFailure(Call<GetCurrenciesModel> call, Throwable t){
}
});
}
Here is the way I use to get data in fragment :
@Override
public void syncCurrencies(List<CurrencyModel> currencies) {
List<FeeItemModel> currency = new ArrayList<>();
for (int i= 0 ; i < currencies.size() ; i++){
currency.add(
new FeeItemModel(
currencies.get(i).getSomething(),
currencies.get(i).getSomething(),
currencies.get(i).getSomething(),
currencies.get(i).getSomething(),
currencies.get(i).getSomething())
); }
CurrenciesAdaptor currenciesAdaptor = new CurrenciesAdaptor(getContext(),currency);
RecyclerView.setAdapter(currenciesAdaptor);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
RecyclerView.setLayoutManager(linearLayoutManager);
RecyclerView.setItemAnimator(new DefaultItemAnimator());
}
but the below method does not run. Note : the Fragment is being created in another place in myActivity too, and even when I try to make a new instance of fragment to make sure it is being created, nothing changes.
Its seems when the data is set in the activity class through the interface object, the fragment might not be attached to the activity .And this seems to not be the correct may to send data from activity to fragment , since this may not every time.
To use the recommended method to send data from activity to fragment use this link:-