今日重点内容是Adnroid的数据存储和访问。Android的数据存储有五种:文件

SharedPreferences、SQLite数据库、内容提供者(Content provider)、网络。今天老黎讲解Android的单元测试、文件存储和访问以及解析XML文件。

 

一、Android的单元测试

       昨天进行的只是简单的开发,但从今天起的开发内容比较重要。所以首先应该学习Android的单元测试。在Android工程中添加单元测试的方法:

       1.向androidManifest.xml加入:

<application>元素体内。是<application>的子元素。

<instrumentation android:name="android.test.InstrumentationTestRunner"
  android:targetPackage="cn.itcast.action" android:label="Tests for My App" />

       </application> 与<application>元素并列,是<application>元素的兄弟元素。这里的targetPackage必须是我们创建工程时指定的包名。

 

       2.单元测试类

       我们的单元测试类,必须继承自AndroidTestCase类。

 

       3.单元测试方法

       单元测试方法必须以test开头

 

       4.方法抛出异常

       方法要throws Throwable异常,Throwable是Exception的父类,单元测试框架捕获Throwable。

 

       5.调用测试

       在outline面板或方法名上右键,Run AS Android Junit Test。

 

       6.打印信息

       在android中不能使用System.out.println()打印信息,但我们可以使用Android为我们提供的Log类来打印信息。可以使用Log.i打开info信息、使用Log.e打印error信息、使用Log.d打印调试信息...。

 

       7.查看打印的信息

       因为我们安装了ADT插件,所以选择菜单windows->Show View->Other...->Android->LogCat,打开 LogCat面板。在这个面板中我们可以看到Android输出的所有信息。

 

       但我们只想查看我们自己输出的信息怎么办呢?面板的右上角有个+号,使用它可以创建一个过滤器。比如我们输入一个info信息调用Log.i(tag,”Hello Android!”),tag是信息的标签,一般使用类名。创建过滤器,将Filter Name和by Log Tag都设置为我的们的tag ,OK。它为我们创建了一个新的以tag名称的分页,在这个分页中我们可以查看过滤出来的信息。

 

       在LogCat面板中还有V、D、I、W、E五个选择按钮,从右向左依次包含。比如我们选择D,那么下面的面板将只显示D、I、W这三类信息。

 

二、Android的文件存储和访问

       Android的文件读写与JavaSE的文件读写相同,都是使用IO流。而且Android使用的正是JavaSE的IO流,下面我们通过一个练习来学习Android的文件读写。

 

       1.创建一个Android工程

Project name:FileRW
       BuildTarget:Android2.1
       Application name:文件读写
       Package name:com.changcheng.File
       Create Activity:FileRW
       Min SDK Version:7

 

       2.编辑strings.xml文件内容:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, FileRW!</string>
    <string name="app_name">文件读写</string>
    <string name="file_name">文件名</string>
    <string name="file_content">文件内容</string>
    <string name="button_file_save">保存</string>
    <string name="button_file_read">读取</string>
    <string name="file_save_success">保存文件成功</string>
    <string name="file_save_failed">保存文件失败</string>
    <string name="file_read_failed">读取文件失败</string>
</resources>

 

       3.编辑main.xml文件内容:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http:///apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
       <!-- 文件名 -->
       <TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="@string/file_name" />
       <EditText android:layout_width="fill_parent"
android:layout_height="wrap_content" android:id="@+id/et_file_name" />
       <!-- 文件内容 -->
       <TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="@string/file_content" />
       <EditText android:layout_width="fill_parent"
android:layout_height="wrap_content" android:minLines="3"
android:id="@+id/et_file_content" />
       <!-- 保存和读取按钮,采用相对布局 -->
       <RelativeLayout android:layout_width="fill_parent"
android:layout_height="wrap_content">
              <!-- 保存按钮 -->
              <Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="@string/button_file_save"
android:id="@+id/bt_save" />
              <!-- 读取按钮 -->
              <Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_toRightOf="@id/bt_save"
android:text="@string/button_file_read" android:id="@+id/bt_read" />
       </RelativeLayout>
</LinearLayout>

 

       4.添加java代码

       Android建议采用MVC开发模式,所以我们在Android应用开发中最好使用MVC设计模式。MVC设计模式使三层分离,从而很好的解耦,何乐而不为。

       首先我们向工程中添加一个FileService.java:

package com.changcheng.file.service;
 
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import android.content.Context;
 
publicclass FileService {
 
       Context context;
 
       public FileService(Context context) {
              this.context = context;
       }
 
       /**
        *
        *
        * @param fileName
        * @param fileContent
        * @throws Exception
        */
       publicvoid save(String fileName, String fileContent) throws Exception {
              // Activity的父类的父类就是context,context与其他框架中的context相同为我们以供了一些核心操作工具。
              FileOutputStream fileOutputStream = this.context.openFileOutput(
                            fileName, Context.MODE_PRIVATE);
              fileOutputStream.write(fileContent.getBytes());
       }
 
       /**
        *
        *
        * @param fileName
        * @return
        * @throws Exception
        */
       public String read(String fileName) throws Exception {
              FileInputStream fileInputStream = this.context.openFileInput(fileName);
              ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
 
              byte[] buffer = newbyte[1024];
              int len = 0;
              while ((len = fileInputStream.read(buffer)) > 0) {
                     byteArray.write(buffer, 0, len);
              };
              return byteArray.toString();
       }
}

      

       Context.MODE_PRIVATE:新内容覆盖原内容

       Context.MODE_APPEND:新内容追加到原内容后

       Context.MODE_WORLD_READABLE:允许其他应用程序读取

       Context.MODE_WORLD_WRITEABLE:允许其他应用程序写入,会覆盖原数据。

       可以使用+连接这些权限。

 

       然后再向工程中添加FileButtonOnClickEvent.java: