Question

I'm attempting to use the method of "internal storage" to retain my data. In the code below I'm trying to write the xml to the storage. Is that the right way to do that? I'm trying to open this file use fileInputStream but the only function of that class that I see for reading is .read() which apparently reads a byte of data at a time. That seems pretty inconvenient for reading an xml file. How should I best read/write my data?

   @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
             FileOutputStream fos=openFileOutput(LOCALSTORAGEFILE,Context.MODE_PRIVATE);
             XmlCreator create=new XmlCreator();
             fos.write(create.subjectListToXml(subjectMasterList).getBytes());
             fos.close();

        } catch (IOException ex) {
            Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);     
        }

public class XmlCreator {
    XmlSerializer serializer=Xml.newSerializer();
    StringWriter writer=new StringWriter();

    public String subjectListToXml(ArrayList<Subject> masterList){
        try{
            serializer.setOutput(writer);
            serializer.startDocument("UTF-8", true);
            serializer.startTag("", "subjects");
            serializer.attribute(null, null, null);
            for(Subject subject:masterList){
                serializer.endTag("","subject");
                for(Cards card:subject.getCards()){
                    serializer.startTag("","card");
                     serializer.startTag("","word");
                     serializer.text(card.getCardFront());
                     serializer.endTag("","word");
                    serializer.endTag("", "card");
                }
                serializer.endTag("", "subject");
            }
                serializer.endTag("","subjects");
                serializer.endDocument();

        }catch(Exception e){
            e.printStackTrace();
        }
        return writer.toString();
    }
}
Was it helpful?

Solution

There's no need to re-invent things. Consider using SharedPreferences.

If you still want to use your XML-format and want to read it the proper way, here's something that will get you started:

InputStream is = ...
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(is);
doc.getDocumentElement().normalize();
NodeList myTags = doc.getElementsByTagName("your_xml_tag");

I can also highly recommend the XML/JSON-library Jackson . It can read and save complete objects using only a few lines of code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top