开发者

Transferring object data from one activity to another activity

I am having a class EmployeeInfo as the following:

 public class EmployeeInfo {
        private int id; // Employee ID
        private String name; // Employee Name
        private int age;// Employee Age

        public int getEmployeeID() {
            return id;
        }

        public void setEmployeeID(int id) {
            this.id = id;
        }

        public String getEmployeeName() {
            return name;
        }

        public void setEmployeeName(String name) {
            this.name = name;
        }
        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age= age;
        }
    }


ArrayList<EmployeeInfo> employeeInfo object contains the emplyoyee info data for multiple employees.

I want to transfer the data( ArrayList employeeInfo ) from Activity1 to Activity2.

Is using Parcelable the only way to transfer the data from Activity1 to Activity2? If not , what are the alternatives.

If yes ,kindly provide the prototype code开发者_StackOverflow社区 of Parcelable along with the sample code on how to transfer the object data from Activity1 to Activity2.


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");


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


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;
    }


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>


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜