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

客户类别的代码:

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

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

我怎样才能做到这一点?


当前回答

使用Serializable实现类。假设这是您的实体类:

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

我们正在将名为dene的对象从X活动发送到Y活动。在X活动的某处;

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

在Y活动中,我们正在获取对象。

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

就是这样。

其他回答

使用gson将对象转换为JSON并通过intent传递。在新的Activity中,将JSON转换为对象。

在build.gradle中,将其添加到依赖项中

implementation 'com.google.code.gson:gson:2.8.4'

在“活动”中,将对象转换为json字符串:

Gson gson = new Gson();
String myJson = gson.toJson(vp);
intent.putExtra("myjson", myjson);

在接收活动中,将json字符串转换回原始对象:

Gson gson = new Gson();
YourObject ob = gson.fromJson(getIntent().getStringExtra("myjson"), YourObject.class);

对于Kotlin来说,这是完全一样的

传递数据

val gson = Gson()
val intent = Intent(this, YourActivity::class.java)
intent.putExtra("identifier", gson.toJson(your_object))
startActivity(intent)

接收数据

val gson = Gson()
val yourObject = gson.fromJson<YourObject>(intent.getStringExtra("identifier"), YourObject::class.java)

不可能序列化任何类型的对象。例如,不能序列化携带代码而不是数据的委托方法或接口。因此,我编写了一个“Box”类,您可以使用它来传递任何类型的数据,而无需序列化。

1-将数据用于预期用途:

Intent I = new Intent(this, YourActivity.class);
CustomClass Date = new CustomClass();
Box.Add(I, "Name", Data);

2-用于从意向检索数据:

CustomClass Data = Box.Get(getIntent(), "Name");

3-要在使用后删除数据,请将此方法添加到活动中:

@Override
protected void onDestroy() {
    Box.Remove(getIntent());
    super.onDestroy();
}

4-并将此代码添加到项目中:

package ir.namirasoft.Utility;

import android.content.Intent;

import java.util.HashMap;
import java.util.Vector;

public class Box {
    // Number
    private static int Number = 1;

    public static int NextNumber() {
        return Number++;
    }

    //
    private static String _Intent_Identifier = "_Intent_Identifier";
    private static HashMap<Integer, Vector<Integer>> DeleteList = new HashMap<Integer, Vector<Integer>>();
    private static HashMap<Integer, HashMap<String, Object>> ObjectList = new HashMap<Integer, HashMap<String, Object>>();

    public static int GetIntent_Identifier(Intent I) {
        int Intent_Identifier = I.getIntExtra(_Intent_Identifier, 0);
        if (Intent_Identifier == 0)
            I.putExtra(_Intent_Identifier, Intent_Identifier = NextNumber());
        return Intent_Identifier;
    }

    public static void Add(Intent I, String Name, Object O) {
        int Intent_Identifier = GetIntent_Identifier(I);
        synchronized (ObjectList) {
            if (!ObjectList.containsKey(Intent_Identifier))
                ObjectList.put(Intent_Identifier, new HashMap<String, Object>());
            ObjectList.get(Intent_Identifier).put(Name, O);
        }
    }

    public static <T> T Get(Intent I, String Name) {
        int Intent_Identifier = GetIntent_Identifier(I);
        synchronized (DeleteList) {
            DeleteList.remove(Intent_Identifier);
        }
        return (T) ObjectList.get(Intent_Identifier).get(Name);
    }

    public static void Remove(final Intent I) {
        final int Intent_Identifier = GetIntent_Identifier(I);
        final int ThreadID = NextNumber();
        synchronized (DeleteList) {
            if (!DeleteList.containsKey(Intent_Identifier))
                DeleteList.put(Intent_Identifier, new Vector<Integer>());
            DeleteList.get(Intent_Identifier).add(ThreadID);
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(60 * 1000);
                } catch (InterruptedException e) {
                }
                synchronized (DeleteList) {
                    if (DeleteList.containsKey(Intent_Identifier))
                        if (DeleteList.get(Intent_Identifier).contains(ThreadID))
                            synchronized (ObjectList) {
                                ObjectList.remove(Intent_Identifier);
                            }
                }
            }
        }).start();
    }
}

**Box类是线程安全的。

这个问题也在另一个堆栈溢出问题中讨论。请查看使用Serializable通过意向传递数据的解决方案。重点是使用Bundle对象,它在Intent中存储必要的数据。

 Bundle bundle = new Bundle();

 bundle.putSerializable(key1, value1);
 bundle.putSerializable(key2, value2);
 bundle.putSerializable(key3, value3);

 intent.putExtras(bundle);

要提取值,请执行以下操作:

 Bundle bundle = new Bundle();

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

Serializable的优点是简单。然而,如果需要传输许多数据,您应该考虑使用Parcelable方法,因为Parcelable是专门为Android设计的,它比Serializable更高效。可以使用以下命令创建Parcelable类:

在线工具parcelablerAndroid Studio插件-Android Parcelable代码生成器

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

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

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

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

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

例如:

Control.Customer = CustomerClass;

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