`

Android之资源文件存取及DOM解析(3)

阅读更多

                   学到这里我们就想到了绝对不能动的R.java文件,对于安卓程序员来说,那是个禁区,是决定不能改动的,那有没有想狮子口拔牙想要把它读出来呢,来我们来试一下。

资源文件的ID都生成在R文件,通过import android.content.res.Resources;将之读出,获取id方法为:

 r=super.getResources();//操作资源

 InputStream input=r.openRawResource(R.raw.mybook);

现在我们自res文件下新建一个raw文件来存出一个资源  mybook.txt,我们实现将之读出,注意定义文本格式选择utf-8,否则读出会是乱码。



 将布局文件设为utf-8,右键properties

布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
   
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/msg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
   />

</LinearLayout>

Activity代码:

 

public class MainActivity extends Activity {

	private TextView text=null;
	private Resources r=null;
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		this.text=(TextView)super.findViewById(R.id.msg);
		r=super.getResources();//操作资源
		InputStream input=r.openRawResource(R.raw.mybook);//读取ID
		Scanner scan=new Scanner(input);
		StringBuffer buf=new StringBuffer();//读取数据
		while(scan.hasNext()){           //循环读取
			buf.append(scan.next()).append("\n");
		}
		scan.close();
		
		try {
			input.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		this.text.setText(buf.toString());
	}

 

实现效果为:



 

  • DOM

使用文件存储固然方便,但是如果数据多了以后,就不太好管理了,现在我们把数据存到xml文件形式进行存储,然后这个格式必须进行解析,解析就要用到DOM解析。

DOM解析虽然我们在android中并不推荐使用,但是这并不代表着不可以实现。dom的原理是把xml文件的各种部分都看成是节点,所有的节点因为层级关系最后形成了一颗节点树。而DOM的解析方式便是在内存中生存这棵树,并允许用户进行相关的操作。

现在我们实现一个目前我们第一个人机交互保存、

就是用户输入资料,程序保存

并必要时可以读出供用户阅览

 

定义DOM,也就是布局文件去解析:

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/TableLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
   
    tools:context=".MainActivity" >

    <TableRow
        android:id="@+id/TableRow01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <TextView
            
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="姓名" />

        <EditText
            android:id="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10" />
    </TableRow>

    <TableRow
        android:id="@+id/tableRow1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/邮箱"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView" />

        <EditText
            android:id="@+id/email"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10" >

            <requestFocus />
        </EditText>

    </TableRow>

    <TableRow
        android:id="@+id/tableRow2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/but"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="保存" />

    </TableRow>

</TableLayout>

  Activity代码:

 

public class MainActivity extends Activity {
	private EditText name = null ;
	private EditText email = null ;
	private Button but = null ;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		super.setContentView(R.layout.activity_main);
		this.name = (EditText) super.findViewById(R.id.name) ;
		this.email = (EditText) super.findViewById(R.id.email) ;
		this.but = (Button) super.findViewById(R.id.but) ;
		this.but.setOnClickListener(new OnClickListenerImpl()) ;
	}
	private class OnClickListenerImpl implements OnClickListener{

		@Override
		public void onClick(View v) {
			if (!Environment.getExternalStorageState().equals(
					Environment.MEDIA_MOUNTED)) {	// 不存在不操作
				return; // 返回到程序的被调用处
			}
			File file = new File(Environment.getExternalStorageDirectory()
					+ File.separator + "eedata" + File.separator
					+ "ee.xml");	// 要输出文件的路径
			if (!file.getParentFile().exists()) { // 父路径不存在
				file.getParentFile().mkdirs() ;	// 创建父文件夹
			}
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance() ;
			DocumentBuilder builder = null ;
			try {
				builder = factory.newDocumentBuilder() ;
			} catch (ParserConfigurationException e) {
				e.printStackTrace();
			}
			Document doc = null ;
			doc = builder.newDocument() ;	// 创建一个新的文档
			Element addresslist = doc.createElement("addresslist") ;
			Element linkman = doc.createElement("linkman") ;
			Element name = doc.createElement("name") ;
			Element email = doc.createElement("email") ;
			name.appendChild(doc.createTextNode(MainActivity.this.name.getText()
					.toString()));
			email.appendChild(doc.createTextNode(MainActivity.this.email.getText()
					.toString()));
			linkman.appendChild(name) ;
			linkman.appendChild(email) ;
			addresslist.appendChild(linkman) ;
			doc.appendChild(addresslist) ;
			TransformerFactory tf = TransformerFactory.newInstance() ;
			Transformer t = null ;
			try {
				t = tf.newTransformer() ;
			} catch (TransformerConfigurationException e) {
				e.printStackTrace();
			}
			t.setOutputProperty(OutputKeys.ENCODING, "GBK") ;
			DOMSource source = new DOMSource(doc);
			StreamResult result = new StreamResult(file) ;
			try {
				t.transform(source, result) ;
			} catch (TransformerException e) {
				e.printStackTrace();
			}
		}
		
	}
}

 

实现效果如下:



 


接下来我们来读取刚才我们保存的文件:

定义类似的布局文件:

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/TableLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TableRow
        android:id="@+id/TableRow01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="姓名" />

        <TextView
            android:id="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </TableRow>

    <TableRow
        android:id="@+id/tableRow1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="邮箱" />

        <TextView
            android:id="@+id/email"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
     />

    </TableRow>

    <TableRow
        android:id="@+id/tableRow2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/but"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="读取" />

    </TableRow>

</TableLayout>

 Activity代码:

public class MainActivity extends Activity {
	private TextView name = null;
	private TextView email = null;
	private Button but = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		super.setContentView(R.layout.activity_main);
		this.name = (TextView) super.findViewById(R.id.name);
		this.email = (TextView) super.findViewById(R.id.email);
		this.but = (Button) super.findViewById(R.id.but);
		this.but.setOnClickListener(new OnClickListenerImpl());
	}

	private class OnClickListenerImpl implements OnClickListener {

		@Override
		public void onClick(View v) {
			if (!Environment.getExternalStorageState().equals(
					Environment.MEDIA_MOUNTED)) { // 不存在不操作
				return; // 返回到程序的被调用处
			}
			File file = new File(Environment.getExternalStorageDirectory()
					+ File.separator + "eedata" + File.separator
					+ "ee.xml"); // 要输出文件的路径
			if (!file.exists()) { // 文件不存在
				return;
			}
			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder builder = null;
			try {
				builder = factory.newDocumentBuilder();
			} catch (ParserConfigurationException e) {
				e.printStackTrace();
			}
			//定义document类对象接口,通过DocumentBuilder进行DOM树转化
			Document doc = null;
			try {
				doc = builder.parse(file); // 通过文件转化文档,读取指定路径的xml文件
			} catch (SAXException e1) {
				e1.printStackTrace();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			//查找节点
			NodeList nl = doc.getElementsByTagName("linkman");
			for (int x = 0; x < nl.getLength(); x++) {
				Element e = (Element) nl.item(x); // 取得元素
				MainActivity.this.name.setText(e.getElementsByTagName("name")
						.item(0).getFirstChild().getNodeValue());
				MainActivity.this.email.setText(e.getElementsByTagName("email")
						.item(0).getFirstChild().getNodeValue());
			}
		}

	}
}

 这一章涉及到很多知识,大家需要好好消化

实现效果如图:




 
 


 
 

 

  • 大小: 3.5 KB
  • 大小: 22.7 KB
  • 大小: 44.9 KB
  • 大小: 27.6 KB
  • 大小: 55 KB
  • 大小: 34.2 KB
  • 大小: 37.8 KB
0
0
分享到:
评论

相关推荐

    android Pull XML文件解析 存取 代码程序

    本篇文章将深入探讨如何在Android中使用Pull解析器进行XML文件的解析和存取。 一、XML解析器简介 在Android中,有两种主要的XML解析方式:SAX(Simple API for XML)和DOM(Document Object Model)。SAX是事件驱动...

    Android基础——XML数据的三种解析方式

    本篇文章将深入探讨XML在Android中的三种主要解析方式:DOM解析、SAX解析和Pull解析,帮助开发者更好地理解和运用这些方法。 1. DOM解析(Document Object Model) DOM解析器会将整个XML文档加载到内存中,形成一个...

    android数据存取xml和数据库

    1. DOM解析:DOM(文档对象模型)解析器将整个XML文件加载到内存中,形成一个树形结构。这种解析方式适用于小规模的XML文件,因为其消耗的内存较大。例如,`DocumentBuilderFactory` 和 `DocumentBuilder` 可用于...

    必看Android 500道高薪面试题集

    15. Android中的五种存储方式:包括SharedPreferences、文件存储、SQLite数据库、ContentProvider和网络存储,每种方式适用于不同场景的数据存取需求。 16. ANR(Application Not Responding):是Android应用无...

    网上总结Android常见面试题

    10. **XML解析**:了解DOM、SAX、PullParser解析方式,官方推荐使用PullParser以提高效率。 在面试中,除了技术知识,面试官还会关注候选人的项目经验、解决问题的能力、沟通技巧等软技能。因此,全面展示自己的...

    【国开搜题】国家开放大学 一网一平台 Android网络开发技术12 期末考试押题试卷.docx

    **详细说明:** Android提供了多种XML解析方式,包括SAX、DOM以及XmlPullParser。Juint不是XML解析库,因此正确答案是C:XmlPullParser。 ### 13. Android AsyncTask 异步任务中的主线程方法 **知识点:** AsyncTask...

    GuiaHollywood:东望洋好莱坞 Android 应用程序

    “东望洋好莱坞”是一款专为Android平台设计的应用程序,旨在为用户提供便捷的电影信息查询、收藏及提醒服务。通过从网络获取HTML内容,该应用能够对数据进行解析,生成详细且实时的电影节目单,满足用户对不同日期...

    BlackBerry开发实例——持久化应用

    BlackBerry提供了`org.w3c.dom`和`javax.xml.parsers`包,用于解析和生成XML文档。你可以创建XML文件来持久化应用的配置信息或其他结构化数据。 4. **BlackBerry Persistent Store**:BlackBerry特有的持久化存储,...

    ionic-course:短期课程如何创建简单的离子应用

    熟悉JavaScript的基本语法、DOM操作和异步编程是开始Ionic之旅的必备技能。在本课程中,学员将学习如何利用JavaScript与Angular的绑定机制,实现数据驱动的界面动态更新。 课程内容可能包括以下几个关键部分: 1. ...

Global site tag (gtag.js) - Google Analytics