我在使用ArrayList<People>
的活动上传递Bundle
(包含大图片)时遇到了一些问题。我失败了因为Bundle
有1MB的限制。
通过一些研究,我发现序列化对象并将其保存到文件会更好,所以我创建了这个类:
public class BundlePeople {
public static long packPeople(Context context, List<People> people) {
long timeToken = System.currentTimeMillis();
String fileName = "temp_" + Long.toString(timeToken);
try {
FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(people);
os.close();
fos.close();
} catch (IOException e) {
Log.e("BundlePeople", e.getMessage());
}
return timeToken;
}
public static List<People> unpackPeople(Context context, long id) {
List<People> list = new ArrayList<>();
String fileName = "temp_" + Long.toString(id);
try {
FileInputStream fis = context.openFileInput(fileName);
ObjectInputStream is = new ObjectInputStream(fis);
list.addAll((List<People>) is.readObject()); //Here I get NotSerializableException on second call
is.close();
fis.close();
} catch (IOException | ClassNotFoundException e) {
Log.e("BundlePeople", e.getMessage());
}
return list;
}
}
它可以运行一次,但是当我再次尝试使用它时,会抛出NotSerializableExcpetion
第一次致电:
传递(FirstActivity.java)
Bundle bundle = new Bundle();
bundle.putLong("peopleFileId", BundlePeople.packPeople(FirstActivity.this, listPeople));
Intent i = new Intent(FirstActivity.this, SecondActivity.class);
i.putExtras(bundle);
startActivityForResult(i.setFlags(SecondActivity.FLAG_SELECT), 0);
接收(SecondActivity.java)
long id = getIntent().getExtras().getLong("peopleFileId");
list = new ArrayList<>();
list.addAll(BundlePeople.unpackPeople(getApplicationContext(), id));
现在它工作正常,问题是我第二次使用它时:
第二次致电:
传递(SecondActivity.java)
Intent i = new Intent();
Bundle b = new Bundle();
b.putLong("peopleFileId", BundlePeople.packPeople(SecondActivity.this, list));
i.putExtras(b);
setResult(REQUEST_PEOPLE, i);
finish();
接收(FirstActivity.java [onActivityResult()])
List<People> list = BundlePeople.unpackPeople(
getApplicationContext(), data.getExtras().getLong("peopleFileId"));
此处我的列表为null
,因为BundlePeople
会在第一个代码上指示的行处抛出异常。
异常消息:Read an exception; java.io.NotSerializableException: br.com.something.activities.SecondActivity$1
我的问题是,为什么我会收到这个例外?这是通过活动传递大型对象的更好方法吗?如果是的话,这里有什么不对?
修改
People.java
public class People implements Serializable {
private static final long serialVersionUID = -9171517741542003990L;
private Integer id;
private String name;
private BitmapSerializable image;
public BitmapSerializable getImage() {
return image;
}
public void setImage(BitmapSerializable image) {
this.image = image;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
答案 0 :(得分:1)
您:
幸运的是,Java在这种情况下将异常写入文件,并在反序列化时将其抛出。异常消息为您提供相关类的名称。
但它应该永远不会有这么远。