安卓操作xml实例

package com.gyarmy.student1;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.xmlpull.v1.XmlSerializer;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Xml;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Toast;

public class MainActivity extends Activity {
	
	private EditText studentNumber;
	private EditText studentName;
	private RadioGroup rgb;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		studentName = (EditText)findViewById(R.id.studentname);
		studentNumber = (EditText)findViewById(R.id.studentnumber);
		rgb  = (RadioGroup)findViewById(R.id.radioGroupsex);
		
	}
	
	public void save(View v){
		String name = studentName.getText().toString().trim();
		String number = studentNumber.getText().toString().trim();
		if(TextUtils.isEmpty(name)||TextUtils.isEmpty(number))
		{
			Toast.makeText(this, "请输入用户名和密码", 1).show();
		}
		
		int id = rgb.getCheckedRadioButtonId();
		String sex= "男";
		if(id == R.id.male)
		{
			sex="男";
			
		}else if(id == R.id.famale){
			sex="女";
		}
		/*
		<?xml version="1.0" encoding="utf-8"?>
		<student>
			<name>George</name>
			<number>John</number>
			<sex>Reminder</sex>
		</student> 
		 * 
		 */
		//保存信息
		//写出
		try {
		File file = new File(this.getFilesDir(),name+".xml");
		OutputStream os = new FileOutputStream(file);

		XmlSerializer serializer = Xml.newSerializer();
		serializer.setOutput(os, "UTF-8");
		
		serializer.startDocument("UTF-8", true);
		serializer.startTag(null, "student");
		
		serializer.startTag(null, "name");
		serializer.text(name);
		serializer.endTag(null, "name");
		
		serializer.startTag(null, "number");
		serializer.text(number);
		serializer.endTag(null, "number");
		
		serializer.startTag(null, "sex");
		serializer.text(sex);
		serializer.endTag(null, "sex");
		
		serializer.endTag(null, "student");
		
		
		serializer.endDocument();
		
		os.close();
		Toast.makeText(this, "录入信息成功", 1).show();
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			Toast.makeText(this, "失败", 1).show();
			e.printStackTrace();
		}
		
		
	}
	
	@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;
	}

}

原文链接: 安卓操作xml实例 版权所有,转载时请注明出处,违者必究。
注明出处格式:流沙团 ( https://gyarmy.com/post-111.html )

发表评论

0则评论给“安卓操作xml实例”