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

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

    Yeah, using a static object is by far the easiest way of doing this with custom non-serialisable objects.

    0 讨论(0)
  • 2020-11-21 04:55

    I had always wondered why this can't be as simple as calling into a method of the other activity. I recently wrote a utility library that makes it almost as simple as that. You can check it out here(https://github.com/noxiouswinter/gnlib_android/wiki/gnlauncher).

    GNLauncher makes sending objects/data to an Activity from another Activity etc as easy as calling a function in tha Activity with the required data as parameters. It introduces type safety and removes all the hastles of having to serialize, attaching to the intent using string keys and undoing the same at the other end.

    Usage

    Define an interface with the methods you want to call on the Activity to launch.

    public interface IPayload {
        public void sayHello(String name, int age);
    }
    

    Implement the above interface on the Activity to launch into. Also notify GNLauncher when the activity is ready.

    public class Activity_1 extends Activity implements IPayload {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            //Notify GNLauncher when the Activity is ready. 
            GNLauncher.get().ping(this);
        }
    
        @Override
        public void sayHello(String name, int age) {
            Log.d("gnlib_test", "Hello " + name + "! \nYour age is: " + age);
        }
    }
    

    In the other Activity, get a proxy to the above Activity and call any method with the desired parameters.

    public class Activity_2 extends Activity {
        public void onClick(View v) {
            ((IPayload)GNLauncher.get().getProxy(this, IPayload.class, Activity_1.class)).sayHello(name, age);
        }
    }
    

    The first activity will be launched and the method called into with the required parameters.

    Prerequisites

    Please refer to https://github.com/noxiouswinter/gnlib_android/wiki#prerequisites for information on how to add the dependencies.

    0 讨论(0)
  • 2020-11-21 04:55

    It is impossible to serialize any type of object. For Example you can not serialize delegate methods or interfaces that carry code instead of data. So I have written a 'Box' class you can use to pass any type of data without Serialization.

    1- for putting Data to Intent Use:

    Intent I = new Intent(this, YourActivity.class);
    CustomClass Date = new CustomClass();
    Box.Add(I, "Name", Data);
    

    2- for retrieving Data from Intent:

    CustomClass Data = Box.Get(getIntent(), "Name");
    

    3- for removing data after use, add this method to your activity:

    @Override
    protected void onDestroy() {
        Box.Remove(getIntent());
        super.onDestroy();
    }
    

    4- and add this code to your project:

    package ir.namirasoft.Utility;
    
    import android.content.Intent;
    
    import java.util.HashMap;
    import java.util.Vector;
    
    public class Box {
        // Number
        private static int Number = 1;
    
        public static int NextNumber() {
            return Number++;
        }
    
        //
        private static String _Intent_Identifier = "_Intent_Identifier";
        private static HashMap<Integer, Vector<Integer>> DeleteList = new HashMap<Integer, Vector<Integer>>();
        private static HashMap<Integer, HashMap<String, Object>> ObjectList = new HashMap<Integer, HashMap<String, Object>>();
    
        public static int GetIntent_Identifier(Intent I) {
            int Intent_Identifier = I.getIntExtra(_Intent_Identifier, 0);
            if (Intent_Identifier == 0)
                I.putExtra(_Intent_Identifier, Intent_Identifier = NextNumber());
            return Intent_Identifier;
        }
    
        public static void Add(Intent I, String Name, Object O) {
            int Intent_Identifier = GetIntent_Identifier(I);
            synchronized (ObjectList) {
                if (!ObjectList.containsKey(Intent_Identifier))
                    ObjectList.put(Intent_Identifier, new HashMap<String, Object>());
                ObjectList.get(Intent_Identifier).put(Name, O);
            }
        }
    
        public static <T> T Get(Intent I, String Name) {
            int Intent_Identifier = GetIntent_Identifier(I);
            synchronized (DeleteList) {
                DeleteList.remove(Intent_Identifier);
            }
            return (T) ObjectList.get(Intent_Identifier).get(Name);
        }
    
        public static void Remove(final Intent I) {
            final int Intent_Identifier = GetIntent_Identifier(I);
            final int ThreadID = NextNumber();
            synchronized (DeleteList) {
                if (!DeleteList.containsKey(Intent_Identifier))
                    DeleteList.put(Intent_Identifier, new Vector<Integer>());
                DeleteList.get(Intent_Identifier).add(ThreadID);
            }
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(60 * 1000);
                    } catch (InterruptedException e) {
                    }
                    synchronized (DeleteList) {
                        if (DeleteList.containsKey(Intent_Identifier))
                            if (DeleteList.get(Intent_Identifier).contains(ThreadID))
                                synchronized (ObjectList) {
                                    ObjectList.remove(Intent_Identifier);
                                }
                    }
                }
            }).start();
        }
    }
    

    ** Box class is Thread-Safe.

    0 讨论(0)
  • 2020-11-21 04:57

    I am using parcelable to send data from one activity to another acivity. Here is my code that works fine in my project.

    public class Channel implements Serializable, Parcelable {
    
        /**  */
        private static final long serialVersionUID = 4861597073026532544L;
    
        private String cid;
        private String uniqueID;
        private String name;
        private String logo;
        private String thumb;
    
    
        /**
         * @return The cid
         */
        public String getCid() {
            return cid;
        }
    
        /**
         * @param cid
         *     The cid to set
         */
        public void setCid(String cid) {
            this.cid = cid;
        }
    
        /**
         * @return The uniqueID
         */
        public String getUniqueID() {
            return uniqueID;
        }
    
        /**
         * @param uniqueID
         *     The uniqueID to set
         */
        public void setUniqueID(String uniqueID) {
            this.uniqueID = uniqueID;
        }
    
        /**
         * @return The name
         */
        public String getName() {
            return name;
        }
    
        /**
         * @param name
         *            The name to set
         */
        public void setName(String name) {
            this.name = name;
        }
    
        /**
         * @return the logo
         */
        public String getLogo() {
            return logo;
        }
    
        /**
         * @param logo
         *     The logo to set
         */
        public void setLogo(String logo) {
            this.logo = logo;
        }
    
        /**
         * @return the thumb
         */
        public String getThumb() {
            return thumb;
        }
    
        /**
         * @param thumb
         *     The thumb to set
         */
        public void setThumb(String thumb) {
            this.thumb = thumb;
        }
    
    
        public Channel(Parcel in) {
            super();
            readFromParcel(in);
        }
    
        public static final Parcelable.Creator<Channel> CREATOR = new Parcelable.Creator<Channel>() {
            public Channel createFromParcel(Parcel in) {
                return new Channel(in);
            }
    
            public Channel[] newArray(int size) {
    
                return new Channel[size];
            }
        };
    
        public void readFromParcel(Parcel in) {
            String[] result = new String[5];
            in.readStringArray(result);
    
            this.cid = result[0];
            this.uniqueID = result[1];
            this.name = result[2];
            this.logo = result[3];
            this.thumb = result[4];
        }
    
        public int describeContents() {
            return 0;
        }
    
        public void writeToParcel(Parcel dest, int flags) {
    
            dest.writeStringArray(new String[] { this.cid, this.uniqueID,
                    this.name, this.logo, this.thumb});
        }
    }
    

    In activityA use it like this:

    Bundle bundle = new Bundle();
    bundle.putParcelableArrayList("channel",(ArrayList<Channel>) channels);
    Intent intent = new Intent(ActivityA.this,ActivityB.class);
    intent.putExtras(bundle);
    startActivity(intent);
    

    In ActivityB use it like this to get data:

    Bundle getBundle = this.getIntent().getExtras();
    List<Channel> channelsList = getBundle.getParcelableArrayList("channel");
    
    0 讨论(0)
  • 2020-11-21 04:59
    public class MyClass implements Serializable{
        Here is your instance variable
    }
    

    Now you want to pass the object of this class in startActivity. Simply use this:

    Bundle b = new Bundle();
    b.putSerializable("name", myClassObject);
    intent.putExtras(b);
    

    This works here because MyClass implements Serializable.

    0 讨论(0)
  • 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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题