編輯:關於 Android 開發
本文示範如何使用 Android 內建的 XmlSerializer 產生 XML 檔案,並以 XmlPullParser 將其解析回物件,完整涵蓋「寫入」與「讀取」兩個環節,並示範 SD 卡路徑的取得與權限設定。
// 取得保存路徑
public File getFilePath() {
File filePath = null;
// 判斷 SD 卡是否存在
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
filePath = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/A_Test/test/");
if (!filePath.isDirectory()) { // 判斷目錄是否存在,不存在就建立
filePath.mkdirs();
}
} else {
Toast.makeText(Main.this, "儲存卡不存在,請插入卡!", 3000).show();
}
return filePath;
}
權限設定:
<!-- SD 卡寫入 --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.DELETE_CACHE_FILES" />
File file = new File(getFilePath() + "/test.xml");
if (!file.exists()) { // 若檔案不存在則建立
List<PersonModel> personModel = new ArrayList<PersonModel>();
personModel.add(new PersonModel(1001, "張三", (short) 30));
personModel.add(new PersonModel(1002, "李四", (short) 18));
personModel.add(new PersonModel(1003, "王二", (short) 21));
CreateXML.createXML(file, personModel);
}
public class CreateXML {
// 生成 XML 檔案
public static void createXML(File file, List<PersonModel> personModel)
throws IllegalArgumentException, IllegalStateException, IOException {
FileOutputStream outputStream = null;
OutputStreamWriter writer = null;
outputStream = new FileOutputStream(file);
writer = new OutputStreamWriter(outputStream, "UTF-8");
BufferedWriter writer2 = new BufferedWriter(writer); // 增加緩衝功能
XmlSerializer serializer = Xml.newSerializer();
serializer.setOutput(writer2);
serializer.startDocument("utf-8", true);
serializer.startTag(null, "persons");
for (PersonModel persons : personModel) {
serializer.startTag(null, "person");
serializer.attribute(null, "id", persons.getId().toString());
serializer.startTag(null, "name");
serializer.text(persons.getName());
serializer.endTag(null, "name");
serializer.startTag(null, "age");
serializer.text(persons.getAge().toString());
serializer.endTag(null, "age");
serializer.endTag(null, "person");
}
serializer.endTag(null, "persons");
serializer.endDocument();
outputStream.close();
}
}
FileInputStream fileInputStream = new FileInputStream(file);
List<PersonModel> personModel = PullXML.pullXML(fileInputStream);
for (int i = 0; i < personModel.size(); i++) {
System.out.println(personModel.get(i).getId() + "--"
+ personModel.get(i).getName() + "--"
+ personModel.get(i).getAge());
}
public class PullXML {
public static List<PersonModel> pullXML(InputStream inStream) throws Throwable {
List<PersonModel> persons = null;
PersonModel person = null;
XmlPullParser parser = Xml.newPullParser(); // 宣告 XML 的 pull 解析器
parser.setInput(inStream, "UTF-8"); // 設定編碼方式
int eventType = parser.getEventType(); // 產生第一個事件
while (eventType != XmlPullParser.END_DOCUMENT) { // 只要不是文件結束事件
switch (eventType) {
case XmlPullParser.START_DOCUMENT: // 文檔開始事件
persons = new ArrayList<PersonModel>();
break;
case XmlPullParser.START_TAG: // 開始元素
String name = parser.getName();
if ("person".equals(name)) {
person = new PersonModel();
person.setId(new Integer(parser.getAttributeValue(0)));
}
if (person != null) {
if ("name".equals(name)) {
person.setName(parser.nextText());
}
if ("age".equals(name)) {
person.setAge(new Short(parser.nextText()));
}
}
break;
case XmlPullParser.END_TAG:
if ("person".equals(parser.getName())) {
persons.add(person);
person = null;
}
break;
}
eventType = parser.next();
}
return persons;
}
}
XmlSerializer 以事件串流的方式逐步寫出標籤與文字,而 XmlPullParser 則以直向(pull)方式逐個事件解析,兩者搭配即可完成輕量級的 XML 讀寫。
用 SurfaceView 播放影片,並搞懂它的生命週期與黑屏問題
用 SurfaceView 播放影片,並搞懂它的生命週期與黑屏問題 本文要利用 SurfaceView 來實作影片播放,並藉此理解 SurfaceView 的生命週期,解
排序演算法總覽:常見做法與複雜度對照
排序是資料結構與演算法面試中的必考題,也是理解時間/空間複雜度權衡的最佳切入點。以下整理幾類主流做法。 以 O(n²) 為起點的三種基礎排序 氣泡排序(Bubbl
自製 StickHeaderListView:解決 footerView 相容問題
自製 StickHeaderListView:解決 footerView 相容問題1、前言:前陣子使用了 GitHub 上 se.emilsjolander.sticky
Android 自定義 ListView 實作教學
Android 自定義 ListView 實作教學ListView 是 Android 早期非常常見的列表元件,適合用來展示大量資料。本文將從系統內建的 ListView