arrayAdapter.add does not keep the previous objects

66 views Asked by At

I am struggling with a problem and read almost all topics about this situation, but I could not find a proper solution to my case. I'll appreciate all suggestions. In my case I am creating a test app and writing the results to a database than I try to get the summary of the results into a ListView. First with an empty List as a global variable I initiate an ArrayList

ArrayList<Results> updatedList = new ArrayList<>();

Than within the onCreateView I initiate the adapter with the empty list. I have a regular CustomAdapter.

ProfileArrayAdapter arrayAdapter = new ProfileArrayAdapter(getContext(), 0, updatedList);

And in another method I update my Object with the new data, and add to arrayAdapter, but unfortunately I tried all possible ways but only last values are added to adapter, and previous ones are deleted. I even use notifyDataSetChanged. Maybe a for loop can be a solution but with the increasing number of items it will be a problem. Please give me some advice on this issue.

    Results aResults = new Results (testIdString, testTypeString, numberOfCorrectAnswers, numberOfFalseAnswers, numberOfEmptyAnswers);
    arrayAdapter.add(aResults); 
    arrayAdapter.notifyDataSetChanged();

Edit: Solution: The problem was everytime the fragment is being called by an TabAdapter for a fragmentPager the list is refreshed. In the Tabadapter I changed new StatisticalFragment with

StatisticsFragment stat = StatisticsFragment.newInstance(StatisticsFragment.updatedList);

Than in the FragmentActivity I used putParcelableArrayList to transmit the array to the new fragment. In order to do this I implemented Parcelable class in my Results class. I hope this solution help someone else.

1

There are 1 answers

4
Ahmet K On

Slm Ömer Kardes,

You have to add your new Object Result aResult firstly to your global ArrayList updatedList. After you add this just call arrayAdapter.notifyDataSetChanged();.

It should kinda look like this :

ArrayList<Results> updatedList = new ArrayList<>();
ProfileArrayAdapter arrayAdapter;
...

public View onCreateView(...){
  arrayAdapter = new ProfileArrayAdapter(getContext(), 0, updatedList);
  ...
}

public void updateList (Result newResult){
  updatedList.add(newResult);
  arrayAdapter.notifyDataSetChanged();
}