您的位置:首页 > 移动开发 > Android开发

Androidx学习笔记(17)-- 数据存储之XML

2016-01-22 18:17 603 查看

使用XML文件备份短信

短信一般需要获取四组数据:号码,内容,时间,类型(发送还是接收)创建几个虚拟的短信对象,存在list中备份数据通常都是备份至sd卡(需要权限)

使用StringBuffer拼接字符串

把整个xml文件所有节点append到sb对象里
sb.append("<?xmlversion='1.0'encoding='utf-8'standalone='yes'?>");
//添加smss的开始节点
sb.append("<smss>");
.......
把sb写到输出流中
fos.write(sb.toString().getBytes());

代码

JavaBean
publicclassMessage{
privateStringbody;//内容
privateStringdate;//时间
privateStringaddress;//对方号码
privateStringtype;//类型1是收到2是发送
publicStringgetBody(){
returnbody;
}
publicvoidsetBody(Stringbody){
this.body=body;
}
publicStringgetDate(){
returndate;
}
publicvoidsetDate(Stringdate){
this.date=date;
}
publicStringgetAddress(){
returnaddress;
}
publicvoidsetAddress(Stringaddress){
this.address=address;
}
publicStringgetType(){
returntype;
}
publicvoidsetType(Stringtype){
this.type=type;
}
publicMessage(Stringbody,Stringdate,Stringaddress,Stringtype){
super();
this.body=body;
this.date=date;
this.address=address;
this.type=type;
}
}
操作
importjava.io.File;
importjava.io.FileNotFoundException;
importjava.io.FileOutputStream;
importjava.util.ArrayList;
importjava.util.List;
importcom.exp.createxml.domain.Message;
importandroid.os.Bundle;
importandroid.app.Activity;
importandroid.view.Menu;
importandroid.view.View;
publicclassMainActivityextendsActivity{
//存放虚拟短信信息
List<Message>smsList;
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//虚拟10条短信
smsList=newArrayList<Message>();
for(inti=0;i<10;i++){
Messagesms=newMessage("Hello"+i,System.currentTimeMillis()+"","138"+i+i,"1");
smsList.add(sms);
}
}
//备份短信
publicvoidclick(Viewv){
//在内存中把xml备份短信的格式拼接出来
StringBuffersb=newStringBuffer();
sb.append("<?xmlversion='1.0'encoding='utf-8'standalone='yes'?>");
sb.append("<messages>");
for(Messagesms: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>");
//将内容保存起来
Filefile=newFile("sdcard/sms.xml");
try{
FileOutputStreamfos=newFileOutputStream(file);
fos.write(sb.toString().getBytes());
fos.close();
}catch(Exceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
}
权限:
<uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: