如果我想将这些数据传递给其他类,我想问一下我做错了什么:
String [] codes = {"code"};
Class<?> [] classes = { TestActivity.class };
Intent i = new Intent();
Pack p = new Pack();
p.eat(classes,codes);
i.putExtra("com.mbar", p);
i.setClass(this, CaptureActivity.class);
startActivity(i);
}
}
稍后在其他活动中,我尝试将其解压缩:
Bundle b = getIntent().getExtras();
Pack p = (Pack)b.getParcelable("com.mbar");
if(p!=null){
classes = p.getClasses();
codes = p.getNames();
Parcelable的Pack类看起来像:
package com.mbar;
import android.os.Parcel;
import android.os.Parcelable;
public class Pack implements Parcelable {
Class<?>[] classes;
String [] codes;
public void eat(Class<?>[] classes,String [] codes){
this.classes = classes;
this.codes = codes;
}
public Class<?>[] getClasses(){
return this.classes;
}
public String [] getNames(){
return this.codes;
}
@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
}
}
答案 0 :(得分:1)
String [] codes = {"code"};
Class<?> [] classes = { TestActivity.class };
Intent i = new Intent();
Pack p = new Pack(classes,codes);
i.putExtra("com.mbar", p);
i.setClass(this, CaptureActivity.class);
startActivity(i)
Pack p = (Pack)getIntent().getParcelableExtra("com.mbar");
if(p!=null){
classes = p.getClasses();
codes = p.getNames();
public static class Pack implements Parcelable {
Class<?>[] classes;
String[] codes;
public Pack(Class<?>[] classes, String[] codes) {
this.classes = classes;
this.codes = codes;
}
public Pack(Parcel in) {
int len = in.readInt();
String[] classnames = new String[len];
in.readStringArray(classnames);
classes = new Class<?>[classnames.length];
for (int i = 0; i < classnames.length; i++) {
try {
classes[i] = Class.forName(classnames[i]);
} catch (ClassNotFoundException e) {
}
}
len = in.readInt();
codes = new String[len];
in.readStringArray(codes);
}
public Class<?>[] getClasses() {
return this.classes;
}
public String[] getNames() {
return this.codes;
}
@Override
public int describeContents() {
return 0;
}
public static final Parcelable.Creator<Pack> CREATOR = new Parcelable.Creator<Pack>() {
public Pack createFromParcel(Parcel in) {
return new Pack(in);
}
public Pack[] newArray(int size) {
return new Pack[size];
}
};
@Override
public void writeToParcel(Parcel dest, int flags) {
String[] classnames = new String[classes.length];
for (int i = 0; i < classes.length; i++) {
classnames[i] = classes[i].getName();
}
dest.writeInt(classnames.length);
dest.writeStringArray(classnames);
dest.writeInt(codes.length);
dest.writeStringArray(codes);
}
}