将对象数据从一个活动转移到另一个活动上[英] Transferring object data from one activity to another activity

本文是小编为大家收集整理的关于将对象数据从一个活动转移到另一个活动上的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我有一个 EmployeeInfo 类,如下所示:

 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.

我想将数据( ArrayList employeeInfo )从 Activity1 传输到 Activity2.

使用 Parcelable 是将数据从 Activity1 传输到 Activity2 的唯一方法吗?如果没有,有什么选择.

如果是,请提供 Parcelable 的原型代码以及如何将对象数据从 Activity1 传输到 Activity2 的示例代码.

推荐答案

这是我对 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];
}

};

}

以及我如何传输数据:

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

并获取数据:

    Bundle data = getIntent().getExtras();
    ProfileData profile = data.getParcelable("profile_details");

其他推荐答案

你可以简单地让你的EmployeeInfo类实现Serializable.或者你可以像这样发送数据

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

如果您需要传输自定义类的列表,我会使用第一种方法.所以你可以把整个列表作为 Serializable.
但是他们说每个人都应该使用 Parcelable 代替,因为它"更快".Tbh,我从来没有用过它,因为它需要更多的努力,我怀疑有人能意识到没有通过意图发送大量数据的常规应用程序的速度差异

其他推荐答案

好问题.查看文档并进行扶手椅编码:

可以通过调用 putExtras(Bundle) 和 myBundle.putSerializable 在活动之间传递对象.对象和整个对象树需要实现可序列化.

日本航空

编辑:答案是肯定的:

可以通过调用 putExtras(Bundle) 和 myBundle.putSerializable 在活动之间传递不可变对象.对象和整个对象树需要实现可序列化.这是面向对象编程的基本原则,即传递有状态的消息.

首先我们通过声明一个新类来创建不可变对象:

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

然后我们在父 Activity 中创建该类的一个不可变的有状态实例,一条消息,并在一个意图中发送它,如下所示:

  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
    }

最后,我们检索子活动中的对象.

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

本文地址:https://www.itbaoku.cn/post/102721.html

问题描述

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