Android XML 序列化

标签 android xml serialization xml-serialization

我正在尝试使用简单的 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/

相关文章:

android - Android Studio 3.1.2 上的 NDK_PROJECT_PATH=null

android - 如何知道每次通话/短信的 SimSlot 号码?

c# - 使用 XML 或 OOP 技术处理数据的相对处理速度是多少? (即 XProc 或 XSL 与 C# 或 Java)

java - 解析 XML 文件时出现异常

java - Tomcat 7 中通过 XML 配置的域间 cookie

jQuery:如何处理可排序 ('serialize' )返回的列表?

android - MediaCodec signalEndOfInputStream() 错误

android - 强制 RTL 布局方向不适用于应用程序

c# - 首次调用 C# Web 服务时速度较慢

java - 有没有像 Schematics (Python) for Java 这样的工具?