package com.example.myxmlmake;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.xmlpull.v1.XmlSerializer;
import com.example.myxmlmake.domain.SmsInfo;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.util.Xml;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
private List<SmsInfo> smsInfos;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
smsInfos = new ArrayList<SmsInfo>();
Random random = new Random();
long number = 135000001;
for(int i=0;i<10;i++)
{
smsInfos.add(new SmsInfo(System.currentTimeMillis(),random.nextInt(2)+1,"短信内容"+i, Long.toString(number++)));
}
}
public void mybackup1(View view)
{
StringBuilder sb = new StringBuilder();
sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
sb.append("<smss>");
for(SmsInfo info : smsInfos)
{
sb.append("<sms>");
sb.append("<address>");
sb.append(info.getAddress());
sb.append("</address>");
sb.append("<type>");
sb.append(info.getType());
sb.append("</type>");
sb.append("<body>");
sb.append(info.getBody());
sb.append("</body>");
sb.append("<date>");
sb.append(info.getDate());
sb.append("</date>");
sb.append("</sms>");
}
sb.append("</smss>");
try{
File file = new File(Environment.getExternalStorageDirectory(),"myback1.xml");
FileOutputStream fos = new FileOutputStream(file);
fos.write(sb.toString().getBytes());
fos.close();
Toast.makeText(this, "生成成功!", 0).show();
}catch(Exception e){
e.printStackTrace();
Toast.makeText(this, "生成失败!", 0).show();
}
}
public void mybackup2(View view)
{
try
{
XmlSerializer serializer = Xml.newSerializer();
File file = new File(Environment.getExternalStorageDirectory(),"myback2.xml");
FileOutputStream os = new FileOutputStream(file);
serializer.setOutput(os,"utf-8");
serializer.startDocument("utf-8", true);
serializer.startTag(null, "smss");
for(SmsInfo info : smsInfos)
{
serializer.startTag(null, "sms");
serializer.startTag(null, "body");
serializer.text(info.getBody());
serializer.endTag(null, "body");
serializer.startTag(null, "address");
serializer.text(info.getAddress());
serializer.endTag(null, "address");
serializer.startTag(null, "type");
serializer.text(info.getType() + "");
serializer.endTag(null, "type");
serializer.startTag(null, "date");
serializer.text(info.getDate() + "");
serializer.endTag(null, "date");
serializer.endTag(null, "sms");
}
serializer.endTag(null, "smss");
serializer.endDocument();
os.close();
Toast.makeText(this, "生成成功!", 0).show();
}catch(Exception e){
e.printStackTrace();
Toast.makeText(this, "生成失败!", 0).show();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}