我正在編寫我自己的android序列化類來將對象轉換爲xml。我創建了一個Bar類,它包含一個酒吧的顏色,Rect和分區。編寫我自己的Android序列化類
public class Bar {
String colour;
int Rect;
int Division;
public Bar(String colour, int Rect, int Division) {
this.colour = colour;
this.Rect = Rect;
this.Division = Division;
}
public String getColour() {
return colour;
}
public int getRect() {
return Rect;
}
public int getDivision() {
return Division;
}
}
在我的主要活動中,我創建了兩個條並將它們添加到數組中。我想遍歷數組並獲取每個條的顏色,並將其寫入一個xml文件。然而,一旦文件被創建寫入到XML文件中的唯一的事情是我的XML header.Below是我的代碼:
public class MainActivity extends Activity {
private String header = "[xmlDoc setVersion:@" + "\" 1.0 \"" + "]" + "\n";
private String barModel = "<barModel>" + "\n";
private String bars = "<bars>" + "\n";
private String bar = "<bar>" + "\n";
private String rect1 = "<rect>";
private String rect2 = "</rect>" + "\n";
private String divisions = "<divisions>";
private String divisions2 = "</divisions>" + "\n";
private String colorId = "<colorId>";
private String colorId2 = "</colorId>" + "\n";
ArrayList<Bar> barList;
Bar David;
Bar Perrine;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addtoArray();
saveModel();
setContentView(R.layout.activity_main);
}
public void addtoArray() {
List<Bar> barList = new ArrayList<Bar>();
barList.add(new Bar("Blue", 33, 8898));
barList.add(new Bar("Red", 6876, 65));
}
protected void saveModel() { // creat directory and file to write to File
File xmlFile = new File(Environment.getExternalStorageDirectory()
.getPath() + "/serializeObject");
xmlFile.mkdirs();
File file = new File(xmlFile, "personmodel.xml");
try {
FileWriter writer = new FileWriter(file);
writer.append(header);
writer.flush();
// iterate through bars
for (Bar array : barList) {
String colour = array.getColour();
writer.append(colorId);
writer.append(colour);
writer.append(colorId2);
writer.flush();
writer.close();
}
} catch (Exception e) {
// Log.d("Downloader", e.getMessage());
}
}
}
誰能幫助我,告訴我,我錯了?
你已經編寫了編寫XML文件的代碼? – Lobo 2013-02-19 15:47:40