How do I save data structures in android?

一笑奈何 提交于 2019-12-10 07:22:29

问题


I want to store some data from structures like this:

class Project {
    ChildA a;
    ChildB b;
}

class ChildA {
    ChildC c;
    ...
}
...

I have created data like:

Projet x = new Project();
x.a = new ChildA();
x.a.c = new ChildC();

... and I want to save it to an external file on the sdcard of my device so that other apps can read it (and users can open/copy it).

I thought I should use a DOM parser because my data structures are not very big, but I find no tutorials or anything like that. Is there a better way to store this information?

If not, are there any instructions how to use the parsers in android?


回答1:


If you want your data to be accessible to other Android applications, then the recommended way is to write a Content Provider. If, on the other hand you want your data to be used in non-android applications, you will need to "export" it. This you have to code on your own.

I can think of three options right now:

  1. Create XML files
    Unfortunately, Android does not include all that is necessary to conveniently create XML files. Most notably, the javax.xml.transform is not available, and adding platform classes is not recommened. That means you will have to write it out on your own "transform" class
  2. Create JSON files
    JSON is well supported by the Android API. See here and here
  3. Create Java serialized files
    As long as your objects implement the interface "Serializable", then they can easily be written out to files. I've never needed to do that myself, but it should be straightforward, and examples should be available on the net. (As an example, Google came up with this mini-tutorial)

When you store your files privately, then consider using openFileInput and openFileOutput. If you want to store explicitly on the SD-Card, you should use getExternalStorageDirectory() to retrieve the root folder.

My personal recommendation would be to use JSON files. It's a simple format which does well for most cases and it's widely available. Apart from that de/serialization is dead-simple.



来源:https://stackoverflow.com/questions/1472898/how-do-i-save-data-structures-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!