getValue() returning null from ViewModel (Java Android) - java

I have been struggling with one bug for a week now. I am a beginner android developer and I am trying to build MVVM app. The idea is to be gaming news but that does not really matter. Here are my 3 classes that are key to this bug.
My NewsFragment class:
FragmentNewsBinding binding;
NewsFragmentAdapter adapter;
Context context;
public NewsFragmentViewModel newsFragmentViewModel;
public NewsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
newsFragmentViewModel = new ViewModelProvider(this).get(NewsFragmentViewModel.class);
// Inflating the layout for this fragment
binding = FragmentNewsBinding.inflate(inflater, container, false);
newsFragmentViewModel.init();
setAdapter(container);
observeChanges();
return binding.getRoot();
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
private void setAdapter(ViewGroup container) {
context = container.getContext();
adapter = new NewsFragmentAdapter(newsFragmentViewModel.getItems().getValue(), context);
RecyclerView.LayoutManager linearLayoutManager = new LinearLayoutManager(context);
binding.recyclerViewNews.setLayoutManager(linearLayoutManager);
binding.recyclerViewNews.setAdapter(adapter);
}
public void observeChanges() {
newsFragmentViewModel.getItems().observe(getViewLifecycleOwner(), new Observer<List<Item>>() {
#Override
public void onChanged(List<Item> items) {
adapter.notifyDataSetChanged();
}
});
}
}
NewsFragmentViewModel class:
public class NewsFragmentViewModel extends ViewModel {
private MutableLiveData<List<Item>> mItems;
private NewsRepository mRepo;
// Empty constructor
public NewsFragmentViewModel() {
}
public void init() {
if (mItems != null) {
return;
}
mRepo = NewsRepository.getInstance();
mItems = mRepo.getItems();
}
public LiveData<List<Item>> getItems() {
return mItems;
}
}
And the repository class:
public class NewsRepository {
MutableLiveData<List<Item>> mItems;
private static NewsRepository instance;
public static NewsRepository getInstance() {
if (instance == null) {
instance = new NewsRepository();
}
return instance;
}
//Empty constructor
private NewsRepository() {
}
public MutableLiveData<List<Item>> getItems() {
mItems = new MutableLiveData<>();
ServiceApi.getInstance().getGamezoneMethods().getGamezoneNews().enqueue(new Callback<Rss>() {
#Override
public void onResponse(Call<Rss> call, Response<Rss> response) {
if (response.code() == 200) {
List<Item> items = response.body().getChannel().getItems();
mItems.postValue(items);
}
}
#Override
public void onFailure(Call<Rss> call, Throwable t) {
Log.d("Failed", "Error");
mItems.postValue(null);
}
});
return mItems;
}
}
Now, the main problem with this code is that in the repository when I do my request I successfully get the data and I think, I successfully push the data to the viewmodel. But when I try to get my data from the LiveData in the viewmodel class or in the fragment class I always get null, and because of the null problem I cannot set up an adapter properly and I cannot set up my onChanged() method. I am trying to get the data in the fragment with the classic getValue() method. Please somebody help me because I am losing my mind.
If you are confused with this code, here is link to my github repo.

Related

Data not displaying through ViewModel

I am newbie to android development and not able to understand why the data is being not displayed. initially the lists are empty so it should show empty text view but it is not showing that also.
Here's the code
Viewmodel factory
public class ViewModelFactoryListItFragment implements ViewModelProvider.Factory {
String category;
Application application;
public ViewModelFactoryListItFragment(Application application,String category ) {
this.category = category;
this.application = application;
}
#NonNull
#Override
public <T extends ViewModel> T create(#NonNull Class<T> aClass) {
if (aClass.isAssignableFrom(ViewModelListItFragment.class)) {
return (T) new ViewModelListItFragment(application, category);
} else throw new IllegalArgumentException("Viewmodel not found");
}
}
ViewModel
public class ViewModelListItFragment extends ViewModel {
private AppDatabase mDb;
private LiveData<List<ListItEntry>> myEntries;
private Application mApplication;
private String mCategory;
public ViewModelListItFragment(#NonNull Application application, String category) {
this.mCategory = category;
this.mApplication = application;
mDb = AppDatabase.getInstance(mApplication);
myEntries = mDb.listItDao().getListItsByCategory(mCategory);
}
public LiveData<List<ListItEntry>> getMyEntries() {
return myEntries;
}
}
Fragment
public class ListItFragment extends Fragment {
private FragmentListItBinding mBinding;
private ViewModelListItFragment mViewModel;
private String mCategory;
public ListItFragment(String category) {
super();
this.mCategory = category;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Timber.i("List it fragment created");
mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_list_it, container, false);
ViewModelFactoryListItFragment factoryListItFragment = new ViewModelFactoryListItFragment(this.getActivity().getApplication(), mCategory);
mViewModel = new ViewModelProvider(this, factoryListItFragment).get(ViewModelListItFragment.class);
LiveData<List<ListItEntry>> entries = mViewModel.getMyEntries();
entries.observe(this.getViewLifecycleOwner(), listItEntries -> {
if(listItEntries == null || listItEntries.size() == 0){
mBinding.textEmpty.setVisibility(View.VISIBLE);
mBinding.recyclerView.setVisibility(View.INVISIBLE);
}
mBinding.textEmpty.setVisibility(View.INVISIBLE);
mBinding.recyclerView.setVisibility(View.VISIBLE);
});
return mBinding.getRoot();
}
I have not yet implemented recylerview adapter so it will not show existing data but when the entries are not there then also it is not showing empty textView.
entries.observe(this.getViewLifecycleOwner(), listItEntries -> {
if(listItEntries == null || listItEntries.size() == 0){
mBinding.textEmpty.setVisibility(View.VISIBLE);
mBinding.recyclerView.setVisibility(View.INVISIBLE);
} else {
mBinding.textEmpty.setVisibility(View.INVISIBLE);
mBinding.recyclerView.setVisibility(View.VISIBLE);
}
});
Your code is outside if part thus even though your condition is met the part outside your if is being executed. Add an else part to make sure that it doesn't get executed as shown above

UI not updated when using SavedStateHandle

Following android's architecture guide, I am experimenting with SavedStateHandle in my view model. So when I post any changes from a thread to the view model, it doesn't reflect on UI. However, without SavedStateHandle the UI changes reflect just fine.
public class UserViewModel extends ViewModel {
UserRepository userRepository;
private static final String USER_KEY = "user_key";
private SavedStateHandle mState;
public UserViewModel(SavedStateHandle savedStateHandle) {
mState = savedStateHandle;
this.userRepository = new UserRepository();
}
public LiveData<String> getUserId() {
return mState.getLiveData(USER_KEY, userRepository.getUserId());
}
public void setUserId(String value) {
mState.set(USER_KEY, value);
}
}
public class UserFragment extends Fragment {
private UserViewModel mViewModel;
public static UserFragment newInstance() {
return new UserFragment();
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.user_fragment, container, false);
}
#Override
public void onViewCreated(#NonNull #NotNull View view, #Nullable #org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mViewModel = new ViewModelProvider(requireActivity()).get(UserViewModel.class);
mViewModel.getUserId().observe(getViewLifecycleOwner(), s -> {
((TextView) view.findViewById(R.id.text_view_1)).setText(s);
});
Executors.newCachedThreadPool().submit(() -> {
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
mViewModel.setUserId("111111");
});
}
public UserViewModel getmViewModel() {
return mViewModel;
}
}
Main Activity
my view only has one framelayout with id sample_fragment
public class MainActivity extends AppCompatActivity {
private final ExecutorService executorService = Executors.newCachedThreadPool();
private UserViewModel userViewModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userViewModel = new ViewModelProvider(this).get(UserViewModel.class);
if (savedInstanceState == null) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
UserFragment userFragment = new UserFragment();
transaction.replace(R.id.sample_fragment, userFragment);
transaction.commit();
executorService.submit(() -> {
try {
Thread.sleep(2000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
userViewModel.setUserId("1");
});
}
}
}
with this code, the changes don't reflect on UI. however when I replace the SaveStateHandle with MutableLiveData then a simple postValue changes the screen just fine. From what I have read, it seems the live data is changed only when the lifecycle is in some specific states (like CREATED).
You set a default value in your getUserId, but I don't see where you use postValue on the data in SavedStateHandle.
I would add a mUserId member and move the code in getUserId to the ViewModel constructor to make sure it's initialized before any write to it. Then make set and post methods:
LiveData<String> mUserId;
public UserViewModel(SavedStateHandle savedStateHandle) {
mState = savedStateHandle;
this.userRepository = new UserRepository();
mUserId = mState.getLiveData(USER_KEY, userRepository.getUserId());
}
public LiveData<String> getUserId() {
return mUserId;
}
public void setUserId(String value) {
mState.getLiveData(USER_KEY).setValue(value);
}
public void postUserId(String value) {
mState.getLiveData(USER_KEY).postValue(value);
}

list is not updating after first call from get API

get API link using retrofit and live data call the first time after some time not updating itself
Call the function on resume in fragment
LiveDataReport used in call retrofit and set the value mutable live
data
Model Fragment used in RecyclerView and adapter
I want get change on anything or updating in get API
immediate change updating RecyclerView list
here my code
Java
public class LiveDataReport {
private static LiveDataReport liveDataReport;
private MutableLiveData<ArrayList<Model>> modelLiveData = new MutableLiveData<>();
private ApiService apiService;
private LiveDataReport() {
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new BasicAuth("user", "pass")).build();
Retrofit retrofit = new Retrofit.Builder()
.client(client)
.baseUrl("http://someipaddress")
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create()).build();
apiService = retrofit.create(ApiService.class);
getModelLiveData();
}
public synchronized static LiveDataReport getInstance() {
if (liveDataReport == null)
liveDataReport = new LiveDataReport();
return liveDataReport;
}
public LiveData<ArrayList<Model>> getModelLiveData() {
Call<ArrayList<Model>> arrayListCall = apiService.getLiveDataJson();
arrayListCall.enqueue(new Callback<ArrayList<Model>>() {
#Override
public void onResponse(#NotNull Call<ArrayList<Model>> call, #NotNullResponse<ArrayList<Model>> response) {
if (response.isSuccessful() && response.body() != null) {
System.out.println("//report change success Model");
modelLiveData.postValue(response.body());
}
}
#Override
public void onFailure(#NotNull Call<ArrayList<Model>> call, #NotNull Throwable t) {
System.out.println("//report change failure " + t.toString());
}
});
return modelLiveData;
}
}
public class MainViewModel extends AndroidViewModel {
private LiveData<ArrayList<Model>> liveData ;
public MainViewModel(#NonNull Application application) {
super(application);
liveData=LiveDataReport.getInstance().getModelLiveData();
}
public LiveData<ArrayList<Model>> getLiveData() {
System.out.println("//report call last update : getModelLiveData");
liveData=LiveDataReport.getInstance().getModelLiveData();
return liveData;
}
}
public class ModelFragment extends Fragment implements LifecycleOwner {
private MainViewModel mainViewModel;
private RecyclerView recyclerView;
private FragmentBinding binding;
private LiveDataAdapter adapter;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment, container, false);
mainViewModel = ViewModelProviders.of(this).get(MainViewModel.class);
recyclerView = binding.myRecycleView;
adapter = new LiveDataAdapter();
recyclerView.setLayoutManager(new LinearLayoutManager(requireContext()));
recyclerView.setHasFixedSize(false);
return binding.getRoot();
}
#Override
public void onResume() {
super.onResume();
if (Utils.isNetWorkConnected(requireContext())) {
mainViewModel.getLiveData().observe(getViewLifecycleOwner(),new Observer<ArrayList<Model>>() {
#Override
public void onChanged(ArrayList<Model> models) {
recyclerView.setAdapter(adapter);
adapter.setModel(models,requireContext());
}
});
} else
Utils.alertCheckNetwork(requireContext());
}
}
public class LiveDataAdapter extends AdapterSkeleton<Model, LiveDataAdapter.CustomViewHolder> {
public LiveDataAdapter(Context context, ArrayList<Model> model, RecyclerView recyclerView, IsCanSetAdapterListener canSetAdapterListener){
this.context=context;
this.items=model;
this.isCanSetAdapterListener=canSetAdapterListener;
measureHeightRecyclerViewAndItem(recyclerView,R.layout.list_model);
}
#NonNull
#Override
public CustomViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
ListModelBinding binding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.list_model, parent, false);
return new CustomViewHolder(binding);
}
#Override
public void onBindViewHolder(#NonNull CustomViewHolder holder, int position) {
if(skeletonConfig.isSkeletonIsOn()){
return;
}
else{
holder.binding.appSkeleton.setShowSkeleton(false);
holder.binding.appSkeleton.finishAnimation();
}
Model model = items.get(position);
holder.binding.setModel(reportStatus);
setAnimation(holder.itemView, position);
}
private void setAnimation(View viewToAnimate, int position) {
Animation animation = AnimationUtils.loadAnimation(context, R.anim.item_animation_fall_down);
viewToAnimate.startAnimation(animation);
}
class CustomViewHolder extends RecyclerView.ViewHolder {
ListModelBinding binding;
public CustomViewHolder(#NonNull ListModelBinding itemView) {
super(itemView.getRoot());
binding = itemView;
}
}
}
updating list does not means it will shown into RecyclerView immediately . you have to manually update RecyclerView as well .
to implement this concept , create a method into your RecyclerView Adapter something like this one below
void updateList(List<POJO> newList) {
oldList = newList;
notifyDataChange();
}
so you will see that your RecyclerView will update , i know that we use livedata to do it automatically but in order to update recyclerView you have to approach this concept .

Using LiveData to manipulate data in RecyclerView from inside a Fragment

I have a RecyclerView in a Fragment where I would like to populate data using MutableLiveData. I have a mock DAO that returns a list of objects of my Model class. The RecyclerView is blank when executed.
This is my mock DAO class:
public class DaoMockFriends implements DaoFriendsInterface {
private ArrayList<FriendsModel> friendsModelsArrayList;
public DaoMockFriends() {
friendsModelsArrayList = new ArrayList<>();
}
#SuppressLint("NewApi")
#Override
public List<FriendsModel> getFriendsList() {
for(int i = 0 ; i < 10 ; i++){
FriendsModel friendsModel = (new FriendsModel("adasdsada"+i,"sdadsadsa"+(i*2),"adsdsadssad"+(i*3),""+(i++), LocalDateTime.now()));
friendsModelsArrayList.add(friendsModel);
}
return friendsModelsArrayList;
}
}
This is my ViewModel class:
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.ViewModel;
import java.util.List;
public class FriendsListLiveDataProvider extends ViewModel {
private MutableLiveData<List<FriendsModel>> friendsModelLiveData = new MutableLiveData<>();
public LiveData<List<FriendsModel>> getFriendsModelLiveData() {
if(this.friendsModelLiveData == null) friendsModelLiveData.postValue(new DaoMockFriends().getFriendsList());
return this.friendsModelLiveData;
}
}
This is my RecyclerViewAdapter class:
public class AdapterFriendsListRecyclerView extends RecyclerView.Adapter<AdapterFriendsListRecyclerView.ViewHolder> {
private List<FriendsModel> listOfFriends;
public AdapterFriendsListRecyclerView(List<FriendsModel> listOfFriends) {
this.listOfFriends = listOfFriends;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.friend_entiry_block,parent,false));
}
#SuppressLint("SetTextI18n")
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
FriendsModel friendsInterface = this.listOfFriends.get(position);
String firstName = friendsInterface.getFirstName();
String lastName = friendsInterface.getLastName();
holder.getTextView().setText(firstName+" "+lastName);
}
#Override
public int getItemCount() {
return listOfFriends.size();
}
public void addItems(List<FriendsModel> friendsInterface){
this.listOfFriends = friendsInterface;
notifyDataSetChanged();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private TextView textView;
public ViewHolder(View itemView) {
super(itemView);
this.textView = itemView.findViewById(R.id.friendEntityNameTV);
}
public TextView getTextView() {
return textView;
}
}
}
This is the implementation in the Fragment :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_friends_list, container, false);
friendsListRV = v.findViewById(R.id.FriendsListRecyclerView);
adapterFriendsListRecyclerView = new AdapterFriendsListRecyclerView(new ArrayList<>());
friendsListRV.setLayoutManager(new LinearLayoutManager(getActivity()));
friendsListRV.setAdapter(adapterFriendsListRecyclerView);
friendsListLiveDataProvider = ViewModelProviders.of(this).get(FriendsListLiveDataProvider.class);
friendsListLiveDataProvider
.getFriendsModelLiveData()
.observe(this, (friendsModels) -> adapterFriendsListRecyclerView
.addItems(friendsModels));
return v;
}
I think that somehow the data from the DAO isn't getting across to the RecyclerViewAdapter. I followed this blog.
How to make the data from the DAO visible in the RecyclerView using LiveData
EDIT:
I changed my ViewModel class as per Yogesh's answer. But my app terminates abruptly without any error or warning messages. When I debug, I found that my app crashes on execution of this line: friendsModelLiveData.postValue(new DaoMockFriends().getFriendsList());
EDIT2:
I tried with the code below in my ViewModel implementation class
public LiveData<List<FriendsModel>> getFriendsModelLiveData() {
if(friendsModelLiveData == null){
friendsModelLiveData = new MutableLiveData<>();
}
loadData();
return this.friendsModelLiveData;
}
private void loadData(){
DaoMockFriends anInterface = new DaoMockFriends();
ArrayList<FriendsModel> fm = anInterface.getFriendsList();
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.submit(new Runnable() {
#Override
public void run() {
friendsModelLiveData.postValue(fm);
}
});
}
The app abruptly terminates at this ArrayList<FriendsModel> fm = anInterface.getFriendsList(); line. I followed this thread to come up with this type of approach.
Method new DaoMockFriends().getFriendsList() never gets executed, because you have initialized friendsModelLiveData at declaration.
Update:
public class FriendsListLiveDataProvider extends ViewModel {
private MutableLiveData<List<FriendsModel>> friendsModelLiveData;
public LiveData<List<FriendsModel>> getFriendsModelLiveData() {
if(this.friendsModelLiveData == null) {
friendsModelLiveData = new MutableLiveData<>();
friendsModelLiveData.postValue(new DaoMockFriends().getFriendsList());
}
return this.friendsModelLiveData;
}
}

Adapter won't update

I am trying to display some items on a recycleView inside a fragment. The items come from another fragment. I first create the recycleView with a empty arrayList but then when a button is pressed, data is sent through interface and a method populates the ArrayList. I have debugged this the whole day and is working perfect, when I hit the button it logs the size of the ArrayList has gone up to one.
I was reading that I have to notify my adapter when the list changes, so I tried using notifyDataSetChange(), notifyItemInserted(dataReceived.size() -1) but neither seem to work out. whenever I check adapter.getItemCount() it throws me 0, even though the arraylist says throws 1.
here's my code inside the fragment Receiving the data:
public class FavoriteFragment extends Fragment {
private OnFragmentInteractionListener mListener;
RecyclerView myRecyclerView;
public ArrayList<RecycleViewItem> dataReceived;
public MyFavoriteAdapter adapter;
public FavoriteFragment() {
}
public void setDataReceived(ArrayList<RecycleViewItem> dataReceived){
this.dataReceived = dataReceived;
Log.d("INTERFACE", "Data received by the FavoriteFragment!!!!" + " " + this.dataReceived.get(0).getCardName());
for(int i = 0; i < dataReceived.size(); i++) {
//THIS LINE RETURNS A 1
Log.d("INTERFACE", "Items inside the dataReceived: " + dataReceived.size());
//NEITHER WORKED
//adapter.notifyItemInserted(dataReceived.size() -1);
//adapter.notifyDataSetChanged();
//THIS LINE WILL KEEP ON RETURNING 0
Log.d("INTERFACE", "Items inside the list inside the adapter: " + adapter.getItemCount());
}
}
public static FavoriteFragment newInstance() {
FavoriteFragment fragment = new FavoriteFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dataReceived = new ArrayList<>();
adapter = new MyFavoriteAdapter(dataReceived);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_favorite, container, false);
myRecyclerView = (RecyclerView) view.findViewById(R.id.recycleView);
myRecyclerView.setHasFixedSize(true);
LinearLayoutManager myLayoutManager = new LinearLayoutManager(getActivity());
myLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
if (myRecyclerView != null) {
myRecyclerView.setAdapter(adapter);
}
myRecyclerView.setLayoutManager(myLayoutManager);
return view;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}
this is the adapter:
public class MyFavoriteAdapter extends RecyclerView.Adapter<MyViewHolder>{
private ArrayList<RecycleViewItem> list = new ArrayList<RecycleViewItem>();
InterfaceListItemClickListener sender = null;
public MyFavoriteAdapter(ArrayList<RecycleViewItem> list) {
this.list = list;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycle_item_favorite, parent, false);
MyViewHolder holder = new MyViewHolder(view, sender);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
if(list.size() >= 1) {
holder.favoriteImageView.setImageResource(list.get(position).getImageResourceID());
holder.favoriteTextView.setText(list.get(position).getCardName());
}
}
#Override
public int getItemCount() {
return list.size();
}
}
Your adapter has a private variable list, and this must be modified for adapter.notifyDataSetChanged() to have any effect.
Here is your method:
public void setDataReceived(ArrayList<RecycleViewItem> dataReceived){
this.dataReceived = dataReceived;
...
}
Assigning the parameter dataReceived to your fragment's this.dataReceived doesn't affect your adapter's list in any way. Rather, you could do something like this instead:
public void setDataReceived(ArrayList<RecycleViewItem> dataReceived){
adapter.list.addAll(dataReceived);
...
}
You may have to make your adapter's list variable public, or expose it via a getter:
public ArrayList<RecycleViewItem> getList() {
return list
}
Or even add a method that can add items to it:
public void addAll(ArrayList<RecycleViewItem> items) {
list.addAll(items);
}
public void setDataReceived(ArrayList dataReceived){
this.dataReceived.addAll(dataReceived);
....
}
Do not recreate list

Categories

Resources