我正在尝试从一个“活动”发送客户类的对象,并在另一个“”中显示它。
客户类别的代码:
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 Test implements Parcelable {
String message;
protected Test(Parcel in) {
message = in.readString();
}
public static final Creator<Test> CREATOR = new Creator<Test>() {
@Override
public Test createFromParcel(Parcel in) {
return new Test(in);
}
@Override
public Test[] newArray(int size) {
return new Test[size];
}
};
public String getMessage() {
return message;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(message);
}
使用Intent发送数据,如下所示:开始活动之前,必须设置一些数据
Intent intent = new Intent(context, PostDetailsActivity.class);
intent.putExtra("data", (Parcelable) test);
((context)).startActivity(intent);
从以下意图中获取数据:
Test test = (Test) getIntent().getParcelableExtra("data");
我使用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");
在自定义类中创建两个方法,如下所示
public class Qabir {
private int age;
private String name;
Qabir(){
}
Qabir(int age,String name){
this.age=age; this.name=name;
}
// method for sending object
public String toJSON(){
return "{age:" + age + ",name:\"" +name +"\"}";
}
// method for get back original object
public void initilizeWithJSONString(String jsonString){
JSONObject json;
try {
json =new JSONObject(jsonString );
age=json.getInt("age");
name=json.getString("name");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
现在在您的发件人活动中这样做
Qabir q= new Qabir(22,"KQ");
Intent in=new Intent(this,SubActivity.class);
in.putExtra("obj", q.toJSON());
startActivity( in);
在您的接收器中活动
Qabir q =new Qabir();
q.initilizeWithJSONString(getIntent().getStringExtra("obj"));
不可能序列化任何类型的对象。例如,不能序列化携带代码而不是数据的委托方法或接口。因此,我编写了一个“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类是线程安全的。
我一直想知道为什么这不能像调用其他活动的方法一样简单。我最近写了一个实用程序库,使它几乎如此简单。你可以在这里查看(https://github.com/noxiouswinter/gnlib_android/wiki/gnlauncher).
GNLauncher使从另一个“活动”等向“活动”发送对象/数据变得简单,就像调用该“活动”中的一个函数并将所需数据作为参数一样。它引入了类型安全性,并消除了所有必须串行化、使用字符串键附加到意图以及在另一端撤消的麻烦。
用法
使用要在要启动的“活动”上调用的方法定义接口。
public interface IPayload {
public void sayHello(String name, int age);
}
在要启动的“活动”上实现上述界面。当活动准备就绪时,也通知GNLauncher。
public class Activity_1 extends Activity implements IPayload {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Notify GNLauncher when the Activity is ready.
GNLauncher.get().ping(this);
}
@Override
public void sayHello(String name, int age) {
Log.d("gnlib_test", "Hello " + name + "! \nYour age is: " + age);
}
}
在另一个“活动”中,获取上述“活动”的代理,并使用所需参数调用任何方法。
public class Activity_2 extends Activity {
public void onClick(View v) {
((IPayload)GNLauncher.get().getProxy(this, IPayload.class, Activity_1.class)).sayHello(name, age);
}
}
将启动第一个活动,并使用所需参数调用方法。
先决条件
请参阅https://github.com/noxiouswinter/gnlib_android/wiki#prerequisites有关如何添加依赖项的信息。