我正在尝试使用简单的 Xml 序列化在我的应用程序中序列化一个对象。( http://simple.sourceforge.net/home.php)。我正在尝试序列化我的 person 类,但是当我在我的设备上运行它时,我找不到我创建的 xml 文件。请在下面查看我的代码:
人类:
public class Person {
public Person() {
}
public Person(String inFirstName, String inLastName) {
SetFirstname(inFirstName);
SetLastname(inLastName);
}
private String FirstName;
public String GetFirstName() {
return FirstName;
}
public void SetFirstname(String inFirstName) {
FirstName = inFirstName;
}
private String LastName;
public String GetLastName() {
return LastName;
}
public void SetLastname(String inLastName) {
LastName = inLastName;
}
@Override
public boolean equals(Object inObject) {
if (inObject instanceof Person) {
Person inPerson = (Person) inObject;
return this.FirstName.equalsIgnoreCase(inPerson.FirstName)
&& this.LastName.equalsIgnoreCase(inPerson.LastName);
}
return false;
}
}
主要 Activity :
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Person person1 = new Person("billy", "boontay");
File xmlFile = new File(getFilesDir().getPath() + "/Person.xml");
try {
Serializer serializer = new Persister();
serializer.write(person1, xmlFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}
谁能看出我哪里出错了?在有人提出建议之前,我已经将写外部存储权限添加到我的 list 中。
最佳答案
File xmlFile = new File(getFilesDir().getPath() + "/Person.xml");
我记得,方法 getFilrsDir() 将返回应用程序文件夹路径,该路径位于 data/data 文件夹中,只有您的设备已 root 后才能找到它,
试试这个:
File xmlFile = new File(Environment.getExternalStorageDirectory().getPath() + "/Person.xml");
也许您还需要在 Person 类中添加一些注释:
@root (name = "person") <br>
public class Person {
@Element (entry = "firstname")
private String FirstName;
@Element (entry = "lastname")
private String LastName;
}
希望这对您有所帮助。
关于Android XML 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14858865/