利用xml文件備份短信
第一:用一個類來描述短信,把每一條短信封裝成一個對象,
package com.itheima.createxml.domain;
public class Message {
private String body;
private String date;
private String address;
private String type;
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Message(String body, String date, String address, String type) {
super();
this.body = body;
this.date = date;
this.address = address;
this.type = type;
}
}
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="備份短信"
android:onClick="click"
/>
第二:短信的xml文件備份格式爲一個個節點存儲的,暫時拼成特定的格式存儲
package com.itheima.createxml;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import com.itheima.createxml.domain.Message;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
public class MainActivity extends Activity {
List<Message> smsList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
smsList = new ArrayList<Message>();
for(int i = 0; i < 10; i++){
Message sms = new Message("小志好棒" + i, System.currentTimeMillis() + "", "138"+i+i, "1");
smsList.add(sms);
}
}
public void click(View v){
StringBuffer sb = new StringBuffer();
sb.append("<?xml version='1.0' encoding='utf-8' standalone='yes' ?>");
sb.append("<messages>");
for (Message sms : smsList) {
sb.append("<sms>");
sb.append("<body>");
sb.append(sms.getBody());
sb.append("</body>");
sb.append("<date>");
sb.append(sms.getDate());
sb.append("</date>");
sb.append("<type>");
sb.append(sms.getType());
sb.append("</type>");
sb.append("<address>");
sb.append(sms.getAddress());
sb.append("</address>");
sb.append("</sms>");
}
sb.append("</messages>");
File file = new File("sdcard/sms.xml");
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write(sb.toString().getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}