0

I have simple DataHolder class:

public class DataHolder
{
    private static final DataHolder holder = new DataHolder();
    Map<String, WeakReference<Object>> data = new HashMap<>();

    public static DataHolder getInstance() {return holder;}

    public void save(String id, Object object)
    {
        data.put(id, new WeakReference<>(object));
    }

    public Object retrieve(String id)
    {
        WeakReference<Object> objectWeakReference = data.get(id);
        return objectWeakReference.get();
    }
}

Basically, I want to hold some data to retrieve them anywhere else (for example, other activity or fragment).

To save:

DataHoler.getInstance().save("list", myList);

To retrieve data:

List<MyObject> list = (ArrayList) DataHoler.getInstance().retrieve("list");

My intent is to avoid passing large amount of data with parcelable (this should be avoided, list may be large) + simplify access to data between all activities/fragments.

Is my approach correct? Not sure if it won't cause any unexpected behaviours or memory leaks.

user1209216
  • 7,404
  • 12
  • 60
  • 123

3 Answers3

0

This approach working well in case of less data, but when large data come in the memory at that time app may not respond properly

0

you can use shared preference to store data. i am adding a link of my previous answer it will be help your answer look this link :- Updating an object stored in one Activity from another activity

Sandeep Malik
  • 1,972
  • 1
  • 8
  • 17
0

I recommend using SoftReference, it is better for caching, objects will live longer. What if GC removes data which you actually needed? WeakReference or SoftReference object can be removed by GC anytime.

Marek Kondracki
  • 1,372
  • 2
  • 8
  • 13
  • Won't GC know if data is needed or not in this case? – user1209216 Apr 16 '19 at 10:33
  • Solution taken from: https://stackoverflow.com/questions/4878159/whats-the-best-way-to-share-data-between-activities/45157829 as far as I understand, GC should not delete it as long as activity that created data exists. This should be garbage collected after activity destroy. – user1209216 Apr 16 '19 at 10:40