Transferring object data from one activity to another activity

前端 未结 5 1244
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-07 08:30

I am having a class EmployeeInfo as the following:

 public class EmployeeInfo {
        private int id; // Employee ID
        private String name; // Employ         


        
相关标签:
5条回答
  • 2021-01-07 08:34

    You can simply let your EmployeeInfo class implement Serializable. Or you can send data like this

    intent.putExtra("id", employInfo.getEmployeeID());
    intent.putExtra("name", employInfo.getEmployeeName());
    intent.putExtra("age", employInfo.getAge());
    

    If you need to transfer a list of your custom classes, i'd use the first approach. So you would be able to put entire list as Serializable.
    However they said that everyone should use Parcelable instead because it's "way faster". Tbh, I'd never used it, because it needs more effort and I doubt somebody can realize the difference in speed in a regular application w/o a load of data sending via intent

    0 讨论(0)
  • 2021-01-07 08:37

    Here is my implementation of Parceleble:

    public class ProfileData implements Parcelable {
    
    private int gender;
    private String name;
    private String birthDate;
    
    public ProfileData(Parcel source) {
        gender = source.readInt();
        name = source.readString();
        birthDate = source.readString();
    }
    
    public ProfileData(int dataGender, String dataName, String dataBDate) {
        gender = dataGender;
        name = dataName;
        birthDate = dataBDate;
    }
    
    // Getters and Setters are here
    
    @Override
    public int describeContents() {
    return 0;
    }
    
    @Override
    public void writeToParcel(Parcel out, int flags) {
    out.writeInt(gender);
    out.writeString(name);
    out.writeString(birthDate);
    }
    
    public static final Parcelable.Creator<ProfileData> CREATOR
          = new Parcelable.Creator<ProfileData>() {
    
    public ProfileData createFromParcel(Parcel in) {
        return new ProfileData(in);
    }
    
    public ProfileData[] newArray(int size) {
        return new ProfileData[size];
    }
    

    };

    }

    and how I transfer data:

    Intent parcelIntent = new Intent().setClass(ActivityA.this, ActivityB.class);
    ProfileData data = new ProfileData(profile.gender, profile.getFullName(), profile.birthDate);
    parcelIntent.putExtra("profile_details", data);
    startActivity(parcelIntent);
    

    and take data:

        Bundle data = getIntent().getExtras();
        ProfileData profile = data.getParcelable("profile_details");
    
    0 讨论(0)
  • 2021-01-07 08:42

    Well there is another way to transfer an object.We can use application to transfer object and this is way is far better way in my opinion.

    First of all create your custom application in your main package.

    public class TestApplication extends Application {
        private Object transferObj;
    
        @Override
        public void onCreate() {
            super.onCreate();
            // ACRA.init(this);
        }
    
        public Object getTransferObj() {
            return transferObj;
        }
    
        public void setTransferObj(Object transferObj) {
            this.transferObj = transferObj;
        }
    
    }
    

    Now use setTransfer and get transfer methods to move abjects from one activity to other like:

    To Transfer:

    ((TestApplication) activity.getApplication()).setTransferObj(Yous object);
    

    ToRecieve:

    Object obj=((TestApplication) activity.getApplication()).getTransferObj();
    

    NOTE Always remember to make entry of this application in manifest application tag:

    <application
            android:name=".TestApplication">
    </application>
    
    0 讨论(0)
  • 2021-01-07 08:44

    You can convert your object to jsonstring using Gson or Jakson and pass using intent as string and read the json in another activity.

    0 讨论(0)
  • 2021-01-07 08:57

    Good question. Looking at the docs and doing armchair coding:

    It may be possible to pass an object between Activities by calling putExtras(Bundle) and myBundle.putSerializable. The object and the entire object tree would need to implement serializable.

    JAL

    EDIT: The answer is yes:

    It is possible to pass an immutable object between Activities by calling putExtras(Bundle) and myBundle.putSerializable. The object and the entire object tree would need to implement serializable. This is a basic tenet of Object Oriented Programming, passing of stateful messages.

    First we create the immutable object by declaring a new class:

    package jalcomputing.confusetext;
    
    import java.io.Serializable;
    
    /*
     * Immutable messaging object to pass state from Activity Main to Activity ManageKeys
     * No error checking
     */
    public final class MainManageKeysMessage implements Serializable {
        private static final long serialVersionUID = 1L;
        public final int lengthPassword;
        public final long timeExpire;
        public final boolean isValidKey;
        public final int timeoutType;
    
        public MainManageKeysMessage(int lengthPassword, long timeExpire, boolean isValidKey, int timeoutType){
            this.lengthPassword= lengthPassword;
            this.timeExpire= timeExpire;
            this.isValidKey= isValidKey;
            this.timeoutType= timeoutType;
        }
    }
    

    Then we create an immutable stateful instance of the class, a message, in the parent activity, and send it in an intent as in:

      private void LaunchManageKeys() {
            Intent i= new Intent(this, ManageKeys.class); // no param constructor
            // push data (4)
            MainManageKeysMessage message= new MainManageKeysMessage(lengthPassword,timeExpire,isValidKey,timeoutType);
            Bundle b= new Bundle();
            b.putSerializable("jalcomputing.confusetext.MainManageKeysMessage", message);
            i.putExtras(b);
            startActivityForResult(i,REQUEST_MANAGE_KEYS); // used for callback
        }
    

    Finally, we retrieve the object in the child activity.

       try {
            inMessage= (MainManageKeysMessage) getIntent().getSerializableExtra("jalcomputing.confusetext.MainManageKeysMessage");
            lengthPassword= inMessage.lengthPassword;
            timeoutType= inMessage.timeoutType;
            isValidKey= inMessage.isValidKey;
            timeExpire= inMessage.timeExpire;
        } catch(Exception e){
            lengthPassword= -1;
            timeoutType= TIMEOUT_NEVER;
            isValidKey= true;
            timeExpire= LONG_YEAR_MILLIS;
        }
    
    0 讨论(0)
提交回复
热议问题