我正在尝试从一个“活动”发送客户类的对象,并在另一个“”中显示它。

客户类别的代码:

public class Customer {

    private String firstName, lastName, address;
    int age;

    public Customer(String fname, String lname, int age, String address) {

        firstName = fname;
        lastName = lname;
        age = age;
        address = address;
    }

    public String printValues() {

        String data = null;

        data = "First Name :" + firstName + " Last Name :" + lastName
        + " Age : " + age + " Address : " + address;

        return data;
    }
}

我想将其对象从一个“活动”发送到另一个“,然后在另一个活动”上显示数据。

我怎样才能做到这一点?


当前回答

public class MyClass implements Serializable{
    Here is your instance variable
}

现在要在startActivity中传递该类的对象。只需使用此选项:

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

这在这里有效,因为MyClass实现了Serializable。

其他回答

我使用parcelable将数据从一个活动发送到另一个活动。这是我的代码,在我的项目中运行良好。

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

在活动A中,如下所示:

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

在ActivityB中,使用如下方法获取数据:

Bundle getBundle = this.getIntent().getExtras();
List<Channel> channelsList = getBundle.getParcelableArrayList("channel");

我知道静态是不好的,但似乎我们不得不在这里使用它。parceables/seriazables的问题是两个活动具有相同对象的重复实例=内存和CPU的浪费。公共类IntentMailBox{静态队列<对象>content=newLinkedList<对象>();}


呼叫活动

IntentMailBox.content.add(level);
Intent intent = new Intent(LevelsActivity.this, LevelActivity.class);
startActivity(intent);

调用的活动(请注意,当系统销毁和重新创建活动时,可能会多次调用onCreate()和onResume())

if (IntentMailBox.content.size()>0)
    level = (Level) IntentMailBox.content.poll();
else
    // Here you reload what you have saved in onPause()

另一种方法是声明要在该类中传递的类的静态字段。它仅用于此目的。不要忘记,在onCreate中它可以为空,因为系统已经从内存中卸载了应用程序包,并在稍后重新加载。请记住,您仍然需要处理活动生命周期,您可能希望将所有数据直接写入共享的首选项,这对于复杂的数据结构来说是很痛苦的。

有几种方法可以访问其他类或Activity中的变量或对象。

A.数据库

B.共享偏好。

C.对象序列化。

可以保存公共数据的类可以命名为公共实用程序。这取决于你。

E.通过Intents和Parcelable接口传递数据。

这取决于您的项目需求。

A.数据库

SQLite是一个嵌入到Android中的开源数据库。SQLite支持标准的关系数据库功能,如SQL语法、事务和准备好的语句。

教程

B.共享偏好

假设您想存储用户名。所以现在有两件事,一个关键用户名,一个值。

如何存储

 // Create object of SharedPreferences.
 SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);

 //Now get Editor
 SharedPreferences.Editor editor = sharedPref.edit();

 //Put your value
 editor.putString("userName", "stackoverlow");

 //Commits your edits
 editor.commit();

使用putString()、putBoolean()、put Int()、putFloat()和putLong(),可以保存所需的数据类型。

如何获取

SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
String userName = sharedPref.getString("userName", "Not Available");

http://developer.android.com/reference/android/content/SharedPreferences.html

C.对象序列化

如果我们希望保存对象状态以通过网络发送,或者您也可以将其用于您的目的,则使用对象序列化。

使用Javabean并将其存储为他的一个字段,并使用getter和setter。

JavaBean是具有财产的Java类。想想作为私有实例变量的财产。因为他们是私人的可以通过类中的方法从类外部访问它们。更改属性值的方法称为setter方法,检索属性值的方式称为getter方法。

public class VariableStorage implements Serializable  {

    private String inString;

    public String getInString() {
        return inString;
    }

    public void setInString(String inString) {
        this.inString = inString;
    }
}

使用

VariableStorage variableStorage = new VariableStorage();
variableStorage.setInString(inString);

然后使用对象序列化来序列化此对象,并在其他类中反序列化此对象。

在串行化中,对象可以表示为一个字节序列,其中包括对象的数据以及关于对象类型和存储在对象中的数据类型的信息。

序列化对象写入文件后,可以从文件中读取并反序列化。也就是说,表示对象及其数据的类型信息和字节可用于在内存中重新创建对象。

如果您需要此教程,请参阅:

Java序列化(博客文章)获取其他类中的变量(堆栈溢出)

D.公用设施

您可以自己创建一个类,其中可以包含项目中经常需要的公共数据。

样品

public class CommonUtilities {

    public static String className = "CommonUtilities";

}

E.通过意图传递数据

有关传递数据的选项,请参考教程Android–使用Parcelable类在活动之间传递包裹数据。

最好的方法是在应用程序中有一个类(称为Control),该类将保存类型为“Customer”的静态变量(在您的情况下)。初始化活动A中的变量。

例如:

Control.Customer = CustomerClass;

然后转到Activity B并从Control类获取它。使用变量后不要忘记赋值null,否则会浪费内存。

正如在评论中提到的,这个答案打破了封装并紧密耦合了组件,这很可能不是您想要的。最好的解决方案可能是使对象可Parcelable或Serializable,正如其他响应所解释的那样。话虽如此,解决方案解决了问题。所以,如果你知道你在做什么:

使用带有静态字段的类:

public class Globals {
    public static Customer customer = new Customer();
}

在活动内部,您可以使用:

活动来源:

Globals.customer = myCustomerFromActivity;

活动目标:

myCustomerTo = Globals.customer;

这是传递活动信息的简单方法。