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

客户类别的代码:

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

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

我怎样才能做到这一点?


当前回答

在Android中,有许多方法可以将对象从一个活动传递到另一个活动。但它们中没有一个可以直接选择通过Intents或Bundles传递对象。您需要做的就是解码对象,作为字符串传递,在NextActivity中编码。示例如下:

Intent i = new Intent(this, nextActivity.class);
i.putExtra("fname", customer.getFirstName());
i.putExtra("lname", customer.getLastName());
i.putExtra("address", customer.getAddress());
startActivity(i);

第二种方法非常简单,使用可以从所有活动轻松访问的静态对象。

第三,最后但并非最不重要的是,您可以将Object存储到某个常量Java文件中,然后从任何活动中读取该Object值。

其他回答

我创建了一个保存临时对象的单例助手类。

public class IntentHelper {

    private static IntentHelper _instance;
    private Hashtable<String, Object> _hash;

    private IntentHelper() {
        _hash = new Hashtable<String, Object>();
    }

    private static IntentHelper getInstance() {
        if(_instance==null) {
            _instance = new IntentHelper();
        }
        return _instance;
    }

    public static void addObjectForKey(Object object, String key) {
        getInstance()._hash.put(key, object);
    }

    public static Object getObjectForKey(String key) {
        IntentHelper helper = getInstance();
        Object data = helper._hash.get(key);
        helper._hash.remove(key);
        helper = null;
        return data;
    }
}

不要将对象放在Intent中,而是使用IntentHelper:

IntentHelper.addObjectForKey(obj, "key");

在新的“活动”中,您可以获取对象:

Object obj = (Object) IntentHelper.getObjectForKey("key");

请记住,一旦加载,对象将被删除,以避免不必要的引用。

使用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)

你可以尝试使用该类。限制是它不能在一个过程之外使用。

一项活动:

 final Object obj1 = new Object();
 final Intent in = new Intent();
 in.putExtra(EXTRA_TEST, new Sharable(obj1));

其他活动:

final Sharable s = in.getExtras().getParcelable(EXTRA_TEST);
final Object obj2 = s.obj();

public final class Sharable implements Parcelable {

    private Object mObject;

    public static final Parcelable.Creator < Sharable > CREATOR = new Parcelable.Creator < Sharable > () {
        public Sharable createFromParcel(Parcel in ) {
            return new Sharable( in );
        }


        @Override
        public Sharable[] newArray(int size) {
            return new Sharable[size];
        }
    };

    public Sharable(final Object obj) {
        mObject = obj;
    }

    public Sharable(Parcel in ) {
        readFromParcel( in );
    }

    Object obj() {
        return mObject;
    }


    @Override
    public int describeContents() {
        return 0;
    }


    @Override
    public void writeToParcel(final Parcel out, int flags) {
        final long val = SystemClock.elapsedRealtime();
        out.writeLong(val);
        put(val, mObject);
    }

    private void readFromParcel(final Parcel in ) {
        final long val = in .readLong();
        mObject = get(val);
    }

    /////

    private static final HashMap < Long, Object > sSharableMap = new HashMap < Long, Object > (3);

    synchronized private static void put(long key, final Object obj) {
        sSharableMap.put(key, obj);
    }

    synchronized private static Object get(long key) {
        return sSharableMap.remove(key);
    }
}

不可能序列化任何类型的对象。例如,不能序列化携带代码而不是数据的委托方法或接口。因此,我编写了一个“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类是线程安全的。

我写了一个名为intentparser的库

它真的很容易使用将此添加到项目等级

allprojects {
        repositories {
            ...
            maven { url 'https://jitpack.io' }
        }
    }

将此添加到应用程序等级


dependencies {
            implementation 'com.github.lau1944:intentparser:v$currentVersion'
    }

使用扩展方法putObject传递对象

val testModel = TestModel(
            text = "hello world",
            isSuccess = false,
            testNum = 1,
            textModelSec = TextModelSec("second model")
)
startActivity(
     Intent(this, ActivityTest::class.java).apply {
          this.putObject(testModel)
     }
) 

从上一个活动获取对象


val testModel = intent.getObject(TestModel::class.java)