Android数据存储之三SQLite嵌入式数据库(2)

本文介绍如何在Android应用中实现SQLite数据库的操作与测试。包括创建数据库表、保存、查找、更新联系人信息等基本功能,并通过编写测试类验证功能的正确性。此外,还介绍了如何使用ListView和SimpleCursorAdapter来分页显示数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

       5. 编写测试类

       编写一个针对ContactsService 的测试类,测试ContactsService 类中的各个方法是否正确。

package com.changcheng.sqlite.test;

 

import java.util.List;

import com.changcheng.sqlite.MyOpenHelper;

import com.changcheng.sqlite.entity.Contact;

import com.changcheng.sqlite.service.ContactsService;

import android.database.Cursor;

import android.test.AndroidTestCase;

import android.util.Log;

 

public class ContactsServiceTest extends AndroidTestCase {

 

         private static final String TAG = "ContactsServiceTest" ;

 

         // 测试创建表

         public void testCreateTable() throws Throwable {

                   MyOpenHelper openHelper = new MyOpenHelper( this .getContext());

                   openHelper.getWritableDatabase();

         }

 

         // 测试save

         public void testSave() throws Throwable {

                   ContactsService contactsService = new ContactsService( this .getContext());

                   Contact contact1 = new Contact( null , "tom" , "13898679876" );

                   Contact contact2 = new Contact( null , "lili" , "13041094909" );

                   Contact contact3 = new Contact( null , "jack" , "13504258899" );

                   Contact contact4 = new Contact( null , "heary" , "1335789789" );

                   contactsService.save(contact1);

                   contactsService.save(contact2);

                   contactsService.save(contact3);

                   contactsService.save(contact4);

         }

 

         // 测试find

         public void testFind() throws Throwable {

                   ContactsService contactsService = new ContactsService( this .getContext());

                   Contact contact = contactsService.find(1);

                   Log.i ( TAG , contact.toString());

         }

 

         // 测试update

         public void testUpdate() throws Throwable {

                   ContactsService contactsService = new ContactsService( this .getContext());

                   Contact contact = contactsService.find(1);

                   contact.setPhone( "1399889955" );

                   contactsService.update(contact);

         }

 

         // 测试getCount

         public void testGetCount() throws Throwable {

                   ContactsService contactsService = new ContactsService( this .getContext());

                   Log.i ( TAG , contactsService.getCount() + "" );

         }

 

         // 测试getScrollData

         public void testGetScrollData() throws Throwable {

                   ContactsService contactsService = new ContactsService( this .getContext());

                   List<Contact> contacts = contactsService.getScrollData(0, 3);

                   Log.i ( TAG , contacts.toString());

         }

        

         // 测试getScrollDataCursor

         public void testGetScrollDataCursor() throws Throwable {

                   ContactsService contactsService = new ContactsService( this .getContext());

                   Cursor cursor = contactsService.getScrollDataCursor(0, 3);

                   while (cursor.moveToNext()) {

                            Contact contact = new Contact(cursor.getInt(0),

                                               cursor.getString(1), cursor.getString(2));

                            Log.i ( TAG , contact.toString());

                   }

         }

 

}

       启用测试功能,不要忘记在AndroidManifest.xml 文件中加入测试环境。为application 元素添加一个子元素:<uses-library android:name="android.test.runner"/> ,为application 元素添加一个兄弟元素:<instrumentation android:name="android.test.InstrumentationTestRunner"      android:targetPackage="com.changcheng.sqlite" android:label="Tests for My App" />

 

       SQLite 数据库以单个文件存储,就像微软的Access 数据库。有一个查看SQLite 数据库文件的工具——SQLite Developer ,我们可以使用它来查看数据库。Android 将创建的数据库存放在”/data/data/ com.changcheng.sqlite/databases/contacts” ,我们将它导出然后使用SQLite Developer 打开。

 

       6. 分页显示数据

       我们在ContactsService 类中,提供了一个获取分页数据的方法。我们将调用它获取的数据,使用ListView 组件显示出来。

 

       编辑mail.xml

<? xml version = "1.0" encoding = "utf-8" ?>

< LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"

         android:orientation = "vertical" android:layout_width = "fill_parent"

         android:layout_height = "fill_parent" >

         <!-- ListView -->

         < ListView android:layout_width = "fill_parent"

                   android:layout_height = "fill_parent" android:id = "@+id/listView" />

 

</ LinearLayout >

 

mail.xml 所在目录里添加一个contactitem.xml

<? xml version = "1.0" encoding = "utf-8" ?>

< RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android"

         android:layout_width = "wrap_content" android:layout_height = "wrap_content" >

 

         <!-- contact.id -->

         < TextView android:layout_width = "30dip" android:layout_height = "wrap_content"

                   android:textSize = "20sp" android:id = "@+id/tv_id" />

 

         <!-- contact.name -->

         < TextView android:layout_width = "150dip" android:layout_height = "wrap_content"

                   android:textSize = "20sp" android:layout_toRightOf = "@id/tv_id"

                   android:layout_alignTop = "@id/tv_id" android:id = "@+id/tv_name" />

 

         <!-- contact.phone -->

         < TextView android:layout_width = "150dip" android:layout_height = "wrap_content"

                   android:textSize = "20sp" android:layout_toRightOf = "@id/tv_name"

                   android:layout_alignTop = "@id/tv_name" android:id = "@+id/tv_phone" />

 

</ RelativeLayout >

 

 

       编辑AndroidSQLite 类:

package com.changcheng.sqlite;

 

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import com.changcheng.sqlite.R;

import com.changcheng.sqlite.entity.Contact;

import com.changcheng.sqlite.service.ContactsService;

import android.app.Activity;

import android.database.Cursor;

import android.os.Bundle;

import android.view.View;

import android.widget.AdapterView;

import android.widget.ListView;

import android.widget.SimpleAdapter;

import android.widget.Toast;

import android.widget.AdapterView.OnItemClickListener;

 

public class AndroidSQLite extends Activity {

         /** Called when the activity is first created. */

         @Override

         public void onCreate(Bundle savedInstanceState) {

                   super .onCreate(savedInstanceState);

                   setContentView(R.layout. main );

                   // 获取分页数据

                   ContactsService contactsService = new ContactsService( this );

                   List<Contact> contacts = contactsService.getScrollData(0, 3);

                   // 获取ListView

                   ListView lv = (ListView) this .findViewById(R.id. listView );

                   // 生成List<? extends Map<String, ?>> 数据

                   List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();

                   for (Contact contact : contacts) {

                            HashMap<String, Object> item = new HashMap<String, Object>();

                            item.put( "_id" , contact.get_id());

                            item.put( "name" , contact.getName());

                            item.put( "phone" , contact.getPhone());

                            data.add(item);

                   }

                   // 生成Adapter

                   SimpleAdapter adapter = new SimpleAdapter( this , data,

                                     R.layout. contactitem , new String[] { "_id" , "name" , "phone" },

                                     new int [] { R.id. tv_id , R.id. tv_name , R.id. tv_phone });

                   // 设置ListView 适配器

                   lv.setAdapter(adapter);

                  

                   //ListView 添加事件

                   lv.setOnItemClickListener( new OnItemClickListener() {

 

                            @Override

                            public void onItemClick(AdapterView<?> parent, View view,

                                               int position, long id) {

                                     HashMap<String, Object> item = (HashMap<String, Object>) parent

                                                        .getItemAtPosition(( int ) id);

                                     Toast.makeText (AndroidSQLite. this , item.get( "name" ).toString(),

                                                        1).show();

                            }

 

                   });

         }

}

 

上面编写的分页显示数据比较麻烦,Android 为我们提供了一个SimpleCursorAdapter 类。使用它可以方便的显示分页数据。将AndroidSQLite 类修改为:

      

package com.changcheng.sqlite;

 

import com.changcheng.sqlite.R;

import com.changcheng.sqlite.service.ContactsService;

import android.app.Activity;

import android.database.Cursor;

import android.os.Bundle;

import android.widget.ListView;

import android.widget.SimpleCursorAdapter;

 

public class AndroidSQLite extends Activity {

         /** Called when the activity is first created. */

         @Override

         public void onCreate(Bundle savedInstanceState) {

                   super .onCreate(savedInstanceState);

                   setContentView(R.layout. main );

 

                   // 获取分页数据

                   ContactsService contactsService = new ContactsService( this );

                   Cursor cursor = contactsService.getScrollDataCursor(0, 3);

                   // 获取ListView

                   ListView lv = (ListView) this .findViewById(R.id. listView );

                   // 创建Adapter

                   SimpleCursorAdapter adapter = new SimpleCursorAdapter( this ,

                                     R.layout. contactitem , cursor, new String[] { "_id" , "name" ,

                                                        "phone" }, new int [] { R.id. tv_id , R.id. tv_name ,

                                                        R.id. tv_phone });

                   // 设置ListView 适配器

                   lv.setAdapter(adapter);

 

                   //ListView 添加事件

                   lv.setOnItemClickListener( new OnItemClickListener() {

 

                            @Override

                            public void onItemClick(AdapterView<?> parent, View view,

                                               int position, long id) {

                                     Cursor cursor = (Cursor) parent

                                                        .getItemAtPosition(( int ) position);

                                     Toast.makeText (AndroidSQLite. this , cursor.getString(1), 1)

                                                        .show();

                            }

                   });

         }

}

 

       OK , 在 Android 中 的 SQLite 操作总结结束!

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值