简体   繁体   中英

Android - hold data in memory with WeakReference

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.

这种方法在数据较少的情况下运行良好,但是当大量数据进入内存时,app可能无法正常响应

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM