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

后端 未结 30 4056
遇见更好的自我
遇见更好的自我 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<String, Object> _hash;
    
        private IntentHelper() {
            _hash = new Hashtable<String, Object>();
        }
    
        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.

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

    Above answers almost all correct but for those who doesn't undestand those answers Android has powerfull class Intent with help of it you share data between not only activity but another components of Android (broadcasr receiver, servises for content provide we use ContetnResolver class no Intent). In your activity you build intent

    Intent intent = new Intent(context,SomeActivity.class);
    intent.putExtra("key",value);
    startActivity(intent);
    

    In your receving activity you have

    public class SomeActivity extends AppCompactActivity {
    
        public void onCreate(...){
        ...
              SomeObject someObject = getIntent().getExtras().getParceable("key");
        }
    
    }
    

    You have to implement Parceable or Serializable interface on your object in order to share between activities. It is hard to implement Parcealbe rather than Serializable interface on object that's why android has plugin especially for this.Download it and use it

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

    While calling an activity

    Intent intent = new Intent(fromClass.this,toClass.class).putExtra("myCustomerObj",customerObj);
    

    In toClass.java receive the activity by

    Customer customerObjInToClass = getIntent().getExtras().getParcelable("myCustomerObj");
    

    Please make sure that customer class implements parcelable

    public class Customer implements Parcelable {
    
        private String firstName, lastName, address;
        int age;
    
        /* all your getter and setter methods */
    
        public Customer(Parcel in ) {
            readFromParcel( in );
        }
    
        public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
            public LeadData createFromParcel(Parcel in ) {
                return new Customer( in );
            }
    
            public Customer[] newArray(int size) {
                return new Customer[size];
            }
        };
    
    
        @Override
        public void writeToParcel(Parcel dest, int flags) {
    
            dest.writeString(firstName);
            dest.writeString(lastName);
            dest.writeString(address);
            dest.writeInt(age);
        }
    
        private void readFromParcel(Parcel in ) {
    
            firstName = in .readString();
            lastName  = in .readString();
            address   = in .readString();
            age       = in .readInt();
        }
    
    0 讨论(0)
  • 2020-11-21 04:47

    Create two methods in your custom Class like this

    public class Qabir {
    
        private int age;
        private String name;
    
        Qabir(){
        }
    
        Qabir(int age,String name){
            this.age=age; this.name=name;
        }   
    
        // method for sending object
        public String toJSON(){
            return "{age:" + age + ",name:\"" +name +"\"}";
        }
    
        // method for get back original object
        public void initilizeWithJSONString(String jsonString){
    
            JSONObject json;        
            try {
                json =new JSONObject(jsonString );
                age=json.getInt("age");
                name=json.getString("name");
            } catch (JSONException e) {
                e.printStackTrace();
            } 
        }
    }
    

    Now in your sender Activity do like this

    Qabir q= new Qabir(22,"KQ");    
    Intent in=new Intent(this,SubActivity.class);
    in.putExtra("obj", q.toJSON());
    startActivity( in);
    

    And in your receiver Activity

    Qabir q =new Qabir();
    q.initilizeWithJSONString(getIntent().getStringExtra("obj"));
    
    0 讨论(0)
  • 2020-11-21 04:50

    Implement your class with Serializable. Let's suppose that this is your entity class:

    import java.io.Serializable;
    
    @SuppressWarnings("serial") //With this annotation we are going to hide compiler warnings
    public class Deneme implements Serializable {
    
        public Deneme(double id, String name) {
            this.id = id;
            this.name = name;
        }
    
        public double getId() {
            return id;
        }
    
        public void setId(double id) {
            this.id = id;
        }
    
        public String getName() {
            return this.name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        private double id;
        private String name;
    }
    

    We are sending the object called dene from X activity to Y activity. Somewhere in X activity;

    Deneme dene = new Deneme(4,"Mustafa");
    Intent i = new Intent(this, Y.class);
    i.putExtra("sampleObject", dene);
    startActivity(i);
    

    In Y activity we are getting the object.

    Intent i = getIntent();
    Deneme dene = (Deneme)i.getSerializableExtra("sampleObject");
    

    That's it.

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

    This question is also discussed in another Stack Overflow question. Please have a look at a solution to Passing data through intent using Serializable. The main point is about using Bundle object which stores the necessary data inside Intent.

     Bundle bundle = new Bundle();
    
     bundle.putSerializable(key1, value1);
     bundle.putSerializable(key2, value2);
     bundle.putSerializable(key3, value3);
    
     intent.putExtras(bundle);
    

    To extract values:

     Bundle bundle = new Bundle();
    
     for (String key : bundle.keySet()) {
     value = bundle.getSerializable(key));
     }
    

    Advantage of Serializable is its simplicity. However, you should consider using Parcelable method if you need many data to be transferred, because Parcelable is specifically designed for Android and it is more efficient than Serializable. You can create Parcelable class using:

    1. an online tool - parcelabler
    2. a plugin for Android Studio - Android Parcelable code generator
    0 讨论(0)
提交回复
热议问题