我試圖使用「內部存儲」的方法來保留我的數據。在下面的代碼中,我試圖將xml寫入存儲。這是正確的方式嗎?我試圖用fileInputStream打開這個文件,但是我看到的讀取類的唯一函數是.read(),它顯然每次讀取一個字節的數據。這看起來很不方便讀取一個XML文件。我應該如何最好地讀/寫我的數據?用xml持久數據,如何實現一個xml讀取器?
@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();
}
}
你已經編寫了'serializer.endTag(「」,「subject」);'在你的代碼中兩次,不應該有一個人說'startTag'? –
是的,謝謝你,錯過了。 –