views:

2174

answers:

1

Hi.

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?

+8  A: 

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.

exhuma