How to pass an object from one activity to another on Android

后端 未结 30 3956
遇见更好的自我
遇见更好的自我 2020-11-21 04:03

I am trying to work on sending an object of my customer class from one Activity and display it in another Activity.

The code for t

30条回答
  •  醉话见心
    2020-11-21 04:43

    I made a singleton helper class that holds temporary objects.

    public class IntentHelper {
    
        private static IntentHelper _instance;
        private Hashtable _hash;
    
        private IntentHelper() {
            _hash = new Hashtable();
        }
    
        private static IntentHelper getInstance() {
            if(_instance==null) {
                _instance = new IntentHelper();
            }
            return _instance;
        }
    
        public static void addObjectForKey(Object object, String key) {
            getInstance()._hash.put(key, object);
        }
    
        public static Object getObjectForKey(String key) {
            IntentHelper helper = getInstance();
            Object data = helper._hash.get(key);
            helper._hash.remove(key);
            helper = null;
            return data;
        }
    }
    

    Instead of putting your objects within Intent, use IntentHelper:

    IntentHelper.addObjectForKey(obj, "key");
    

    Inside your new Activity, you can get the object:

    Object obj = (Object) IntentHelper.getObjectForKey("key");
    

    Bear in mind that once loaded, the object is removed to avoid unnecessary references.

提交回复
热议问题