What is the correct way to share data between different Activities or Fragments?

前端 未结 1 1380
一生所求
一生所求 2021-01-03 03:36

I need an app that should have a UI workflow where in a user should be able to browse a particular section of the app which can be either a ListView or a GridView and where

相关标签:
1条回答
  • 2021-01-03 04:05

    Android provides mapping from String values to various Parcelable types using Bundle.

    For activity:-

    Intent in = new Intent(Sender.this, Receiver.class); 
    in.putString(key, value)
    startActivity(in);
    

    For Fragment use Bundle:-

    Fragment fragment = new Fragment(); 
    Bundle bundle = new Bundle();
    bundle.putInt(key, value);
    fragment.setArguments(bundle);
    

    Edit for your scenario : I think the better option is create ApplicationPool.

    Follow the below steps:- Initiate the ApplicationPool :-

    ApplicationPool pool = ApplicationPool.getInstance();
    

    modify the data on details page and add to pool

    pool.put("key", object);
    

    get the modified data on list page from pool

    Object  object = (Object) pool.get("key");
    

    important notes:- notify the listview or gridview after getting the data

    ApplicationPool class file

    public class ApplicationPool {
    
        private static ApplicationPool instance;
        private HashMap<String, Object> pool;
    
        private ApplicationPool() {
            pool = new HashMap<String, Object>();
        }
    
        public static ApplicationPool getInstance() {
    
            if (instance == null) {
                instance = new ApplicationPool();
    
            }
    
            return instance;
        }
    
        public void clearCollectionPool() {
            pool.clear();
        }
    
        public void put(String key, Object value) {
            pool.put(key, value);
        }
    
        public Object get(String key) {
            return pool.get(key);
        }
    
        public void removeObject(String key) {
    
            if ((pool.get(key)) != null)
                pool.remove(key);
    
        }
    }
    
    0 讨论(0)
提交回复
热议问题