前端之家收集整理的这篇文章主要介绍了
利用XML文件备份短信---手动拼字符串,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
利用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();
}
}
}