我正在编写自己的 android 序列化类来将对象转换为 xml。我创建了一个 Bar 类,它由条形的颜色、矩形和除法组成。
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 标头。下面是我的代码:
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());
}
}
}
谁能帮助我并告诉我哪里出错了?