我有一个相当简单的课程。
package com.example.myapp;
public class Preset implements Serializable{
/**
* Gernerated Serial Id For Serialization
*/
private static final long serialVersionUID = -183094847073879300L;{
private String name;
private int id;
private float speed;
private boolean moving;
public Preset(String name, int id, float speed, boolean moving){
this.name = name;
this.id = id;
this.speed = speed;
this.moving = moving;
}
public String getName(){
return this.name;
}
public int getId(){
return this.id;
}
}
我有另一个类创建这些预设的列表
public class PresetList extends PreferenceActivity implements Serializable{
/**
* Default Serial Id for Serialization
*/
private static final long serialVersionUID = 1L;
private List<Preset> presetList = new ArrayList<Phys>();
private int listSize = 0;
/* Constructor */
public PresetList(){
// Allows Access To Our List
}
public void addToList(Preset p){
presetList.add(p);
listSize++;
saveList(presetList);
}
public void removeFromList(int listLocation){
presetList.remove(listLocation);
listSize--;
saveList(presetList);
}
public int getListSize(){
return listSize;
}
在同一个类中调用这些方法
/* Save Object Through Serialization */
@SuppressLint("SdCardPath")
public void saveList(List<Preset> pl){
try
{
String fileName = Environment.getExternalStorageDirectory() + File.separator +
"Android" + File.separator + "data" + File.separator + "presets_list.bin";
File presetListFile = new File(fileName);
try{
presetListFile.createNewFile();
}
catch (IOException e){
Log.d("IOException", "File exception " + e.getMessage());
}
ObjectOutputStream outputStream = new ObjectOutputStream(
new FileOutputStream(presetListFile)); //Select where you wish to save the file...
outputStream.writeObject(pl); // write the class as an 'object'
outputStream.flush(); // flush the stream to insure all of the information was written to 'save_object.bin'
outputStream.close();// close the stream
}
catch(Exception e)
{
Log.d("IOException","Serialization Write Error: " + e.getMessage());
}
}
// Retrieve List through Desearialization
@SuppressWarnings("unchecked")
public List<Preset> loadList(File f){
try
{
ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream (f));
Object o = inputStream.readObject();
presetList= (List<Preset>) o;
return presetList;
}
catch(Exception e){
Log.d("IOException", "Serialization Read Error : " + e.getMessage());
}
return null;
}
}
当我尝试创建列表时,出现错误
Serialization Read Error : Read an exception; java.io.NotSerializableException: com.example.myapp.Preset
我哪里错了?如果它不可序列化,它在尝试读取之前如何写入?