【发布时间】:2016-05-03 10:40:58
【问题描述】:
所以,我尝试序列化一个对象并将其作为 XML 写入文件中,并且效果很好。因此,当我尝试读取该 XML 文件并将其反序列化为类对象时,我得到一个空引用异常。
我正在研究这个示例http://www.rhyous.com/2011/10/23/android-and-xml-serialization-with-simple/,它可以工作,但这只是一个简单的类。
在我的例子中,有两个类,其中一个有一个类型为第二类的对象列表。
这是任务类:
@Root (name = "Task")
public class Task {
@Element
public String Name;
@Element
public int Image;
@ElementList (type = Item.class)
public ArrayList<Item> Items;
@Element
boolean IsChecked;
Task(){}
Task(String name, int image, ArrayList<Item> items, boolean isChecked){
this.Name = name;
this.Image = image;
this.Items = items;
this.IsChecked = isChecked;
}
}
这是 Item 类:
@Root (name = "Item")
public class Item {
@Element
public String Name;
@Element
public String Image;
@Element
public boolean IsChecked;
@Element
public String Description;
Item(String name, String image, String description) {
this.Name = name;
this.Image = image;
this.IsChecked = false;
this.Description = description;
}
Item(String name, String image, boolean isChecked, String description) {
this.Name = name;
this.Image = image;
this.IsChecked = isChecked;
this.Description = description;
}
}
这是主要活动:
public class MainActivity extends AppCompatActivity {
private static final String APP_DIR_PATH = Environment.getExternalStorageDirectory() + File.separator + "MyApp";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<Item> items = new ArrayList<Item>();
items.add(new Item("firstItem", APP_DIR_PATH + "/firstPic.jpg", "firstDescription"));
items.add(new Item("secondItem", APP_DIR_PATH + "/secondPic.jpg", "secondDescription"));
items.add(new Item("thirdItem", APP_DIR_PATH + "/thirdPic.jpg", "thirdDescription"));
Task firstTask = new Task("firstTask", 1, items, true);
// Serialization and writing to file
File xmlFile = new File(APP_DIR_PATH + "/Task.xml");
try {
Serializer serializer = new Persister();
serializer.write(firstTask, xmlFile);
} catch (Exception e) {
e.printStackTrace();
}
// Deserialization and reading from file
Task secondTask = null;
if (xmlFile.exists()) {
try {
Serializer serializer = new Persister();
secondTask = serializer.read(Task.class, xmlFile);
} catch (Exception e) {
e.printStackTrace();
}
}
// This throws a null reference exception
Toast.makeText(getBaseContext(), secondTask.Name, Toast.LENGTH_SHORT).show();
// If I try to serialize the object and write it to file, the file is empty, but that's to be expected :)
File secondXmlFile = new File(APP_DIR_PATH + "/secondTask.xml");
try {
Serializer serializer = new Persister();
serializer.write(secondTask, secondXmlFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}
【问题讨论】:
标签: java android xml serialization