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

后端 未结 30 3948
遇见更好的自我
遇见更好的自我 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:59

    You can try to use that class. The limitation is that it can't be used outside of one process.

    One activity:

     final Object obj1 = new Object();
     final Intent in = new Intent();
     in.putExtra(EXTRA_TEST, new Sharable(obj1));
    

    Other activity:

    final Sharable s = in.getExtras().getParcelable(EXTRA_TEST);
    final Object obj2 = s.obj();
    
    public final class Sharable implements Parcelable {
    
        private Object mObject;
    
        public static final Parcelable.Creator < Sharable > CREATOR = new Parcelable.Creator < Sharable > () {
            public Sharable createFromParcel(Parcel in ) {
                return new Sharable( in );
            }
    
    
            @Override
            public Sharable[] newArray(int size) {
                return new Sharable[size];
            }
        };
    
        public Sharable(final Object obj) {
            mObject = obj;
        }
    
        public Sharable(Parcel in ) {
            readFromParcel( in );
        }
    
        Object obj() {
            return mObject;
        }
    
    
        @Override
        public int describeContents() {
            return 0;
        }
    
    
        @Override
        public void writeToParcel(final Parcel out, int flags) {
            final long val = SystemClock.elapsedRealtime();
            out.writeLong(val);
            put(val, mObject);
        }
    
        private void readFromParcel(final Parcel in ) {
            final long val = in .readLong();
            mObject = get(val);
        }
    
        /////
    
        private static final HashMap < Long, Object > sSharableMap = new HashMap < Long, Object > (3);
    
        synchronized private static void put(long key, final Object obj) {
            sSharableMap.put(key, obj);
        }
    
        synchronized private static Object get(long key) {
            return sSharableMap.remove(key);
        }
    }
    

提交回复
热议问题