创建xml文件(传统)

前端之家收集整理的这篇文章主要介绍了创建xml文件(传统)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

xml格式如下:



创建Button监听器

<Button
        android:onClick="backSms"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="短信的备份" />

创建model层:SmsInfo类(有参无参构造方法,getset对儿)

<span style="white-space:pre">	</span>private long date; // 短信时间
	private int type; // 短信类型(1代表发送,2代表接收)
	private String body; // 短信内容
	private String address; // 短信收(发)件人地址


package org.gentry.writexml;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.gentry.writexml.domain.SmsInfo;

import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
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 = 1350000000;
		for (int i = 0; i < 10; i++) {
			smsInfos.add(new SmsInfo(System.currentTimeMillis(),random
					.nextInt(2) + 1,"短信内容" + i,Long.toString(number + i)));
		}
	}

	/**
	 * 备份手机的短信
	 * 
	 * @param view
	 */
	public void backSms(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("<data>");
			sb.append(info.getDate());
			sb.append("</data>");
			
			sb.append("</sms>");
		}
		sb.append("</smss>");

		try {
			File file = new File(Environment.getExternalStorageDirectory(),"backup.xml");
			FileOutputStream fos = new FileOutputStream(file);
			fos.write(sb.toString().getBytes());
			fos.close();
			Toast.makeText(this,"备份成功",Toast.LENGTH_SHORT).show();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Toast.makeText(this,"备份失败",Toast.LENGTH_SHORT).show();
		}

	}
}
原文链接:https://www.f2er.com/xml/298299.html

猜你在找的XML相关文章