如果使用Sqlite,建议和ContentProvider结合使用。这样数据库的生命周期就不用自己管了。然后,如果要在比如ListView中显示,可以使用CursorAdapter。简化的办法是使用子类SimpleCursorAdapter。
以下就介绍一下使用sqlite+content provider+cursor adapter的最简单实现示例。太简单了,示例如图:
首先,要有个Content provider,如不了解如何实现,请参考编写最简单的Content Provider和在Content provider实现中使用SQLiteOpenHelper,下面写的是结合二者的:
1. public class RiverContentProvider extends ContentProvider {
2.  
3.     public static final Uri CONTENT_URI = Uri 
4.             .parse("content://com.easymorse.cp.rivers");
5.  
6.     public static final String _ID = "_id";
7.  
8.     public static final String NAME = "name";
9.  
10.     public static final String LENGTH = "length";
11.  
12.     private static SQLiteDatabase database;
13.  
14.     private static final int DATABASE_VERSION = 2;
15.  
16.     private static final List<River> RIVERS = new ArrayList<River>();
17.  
18.     static { 
19.         River river = new River("长江", 6380); 
20.         RIVERS.add(river);
21.  
22.         river = new River("黄河", 5464); 
23.         RIVERS.add(river); 
24.     }
25.  
26.     @Override 
27.     public int delete(Uri uri, String selection, String[] selectionArgs) { 
28.         // TODO Auto-generated method stub 
29.         return 0; 
30.     }
31.  
32.     @Override 
33.     public String getType(Uri uri) { 
34.         // TODO Auto-generated method stub 
35.         return null; 
36.     }
37.  
38.     @Override 
39.     public Uri insert(Uri uri, ContentValues contentValues) { 
40.         // TODO Auto-generated method stub 
41.         return null; 
42.     }
43.  
44.     @Override 
45.     public boolean onCreate() { 
46.         database = new RiverDatabaseHelper(getContext(), "rivers", null, 
47.                 DATABASE_VERSION).getReadableDatabase(); 
48.         return database != null; 
49.     }
50.  
51.     @Override 
52.     public Cursor query(Uri uri, String[] projection, String selection, 
53.             String[] selectionArgs, String sortOrder) { 
54.         return database.query("rivers", projection, selection, selectionArgs, 
55.                 null, null, sortOrder); 
56.     }
57.  
58.     @Override 
59.     public int update(Uri uri, ContentValues values, String selection,
60.             String[] selectionArgs) { 
61.         // TODO Auto-generated method stub 
62.         return 0; 
63.     }
64.  
65.     private static class RiverDatabaseHelper extends SQLiteOpenHelper {
66.  
67.         public RiverDatabaseHelper(Context context, String name, 
68.                 CursorFactory factory, int version) { 
69.             super(context, name, factory, version); 
70.         }
71.  
72.         @Override 
73.         public void onCreate(SQLiteDatabase database) { 
74.             database.execSQL("create table if not exists rivers(" 
75.                     + " _id integer primary key autoincrement," + " name text," 
76.                     + "length integer" + ");");
77.  
78.             SQLiteStatement statement = database 
79.                     .compileStatement("insert into rivers(name,length) values(?,?)");
80.  
81.             for (River r : RIVERS) { 
82.                 int index = 1; 
83.                 statement.bindString(index++, r.getName()); 
84.                 statement.bindLong(index++, r.getLength()); 
85.                 statement.executeInsert(); 
86.             }
87.  
88.             statement.close(); 
89.         }
90.  
91.         @Override 
92.         public void onUpgrade(SQLiteDatabase database, int oldVersion, 
93.                 int newVersion) { 
94.             database.execSQL("drop table if exists rivers"); 
95.             onCreate(database); 
96.         }
97.  
98.     }
复制代码
 
这里写的很简略,没用到的方法都没实现。在总的布局中使用了ListView:
1. <?xml version="1.0" encoding="utf-8"?>
2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. android:orientation="vertical" android:layout_width="fill_parent"
4. android:layout_height="fill_parent">
5. <ListView android:id="@+id/riverList" android:layout_width="fill_parent"
6. android:layout_height="fill_parent" />
7. </LinearLayout>
 
复制代码
  
 
使用了自定义的ListView布局,见:
 
1. <?xml version="1.0" encoding="utf-8"?>
2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. android:layout_width="match_parent" android:layout_height="wrap_content">
4. <TextView android:id="@+id/riverName" android:layout_width="match_parent"
5. android:layout_height="wrap_content" />
6. </LinearLayout>
复制代码
  
 
最后是在Activity中使用contentprovider查询的cursor,生成ListView:
 
1. public class ListViewActivity extends Activity {
2.     private ListView riverListView;
3.     /** Called when the activity is first created. */ 
4.     @Override 
5.     public void onCreate(Bundle savedInstanceState) { 
6.         super.onCreate(savedInstanceState); 
7.         setContentView(R.layout.main);
8.         setRiverListViewAdapter(); 
9.     }
10.     private void setRiverListViewAdapter() { 
11.         riverListView = (ListView) this.findViewById(R.id.riverList);
12.         Cursor cursor = managedQuery(RiverContentProvider.CONTENT_URI, null, 
13.                 null, null, null); 
14.         CursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.row, 
15.                 cursor, new String[] { RiverContentProvider.NAME }, 
16.                 new int[] { R.id.riverName }); 
17.         riverListView.setAdapter(adapter); 
18.     } 
19. } 
复制代码
  
 源代码见: <ignore_js_op style="word-wrap: break-word; ">
简约而不简单——Android SimpleAdapter
  
列表(ListView)、表格(GridView),这在手机应用上面肯定是少不了的,怎样实现比较复杂一点的界面呢,先看一下我的效果图。

 

这样布局的情况是最基本的,也是最常用的,网上关于这样的布局有多种版本的实现方法,但是有很多需要自己实现Adapter,那样子是比较复杂而且没有必要的,因为我们有简约而不简单的SimpleAdapter。
1. ListView
SimpleAdapter的核心代码:
   
for (int i = 0; i < 10; i++) {
      Map<String, Object> map = new HashMap<String, Object>();
      map.put("PIC", R.drawable.pic);
      map.put("TITLE", "Test Title");
      map.put("CONTENT", "Test Content");
      contents.add(map);
    }
    SimpleAdapter adapter = new SimpleAdapter(this,
        (List<Map<String, Object>>) contents, R.layout.listitem,
        new String[] { "PIC", "TITLE", "CONTENT" }, new int[] {
            R.id.listitem_pic, R.id.listitem_title,
            R.id.listitem_content });
    listView.setAdapter(adapter);   
listitem的Layout:
   
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="?android:attr/listPreferredItemHeight">
<ImageView android:id="@+id/listitem_pic"
android:layout_width="wrap_content" android:layout_height="fill_parent"
android:layout_alignParentTop="true" android:layout_alignParentBottom="true"
android:src="@drawable/pic" android:adjustViewBounds="true"
android:padding="2dip" />
<TextView android:id="@+id/listitem_title"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_toRightOf="@+id/listitem_pic"
android:layout_alignParentRight="true" android:layout_alignParentTop="true"
android:layout_above="@+id/listitem_content"
android:layout_alignWithParentIfMissing="true" android:gravity="center_vertical"
android:text="@+id/listitem_title" android:textSize="22px" />
<TextView android:id="@+id/listitem_content"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:layout_toRightOf="@+id/listitem_pic"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true" android:singleLine="true"
android:ellipsize="marquee" android:text="@+id/item_content"
android:textSize="14px" />
</RelativeLayout>
   
2. GridView
SimpleAdapter的核心代码:
   
for (int i = 0; i < 10; i++) {
      Map<String, Object> map = new HashMap<String, Object>();
      map.put("PIC", R.drawable.pic);
      map.put("TITLE", "Test Title");
      contents.add(map);
    }
    SimpleAdapter adapter = new SimpleAdapter(this,
        (List<Map<String, Object>>) contents, R.layout.griditem,
        new String[] { "PIC", "TITLE" }, new int[] { R.id.griditem_pic,
            R.id.griditem_title, });
    gridView.setAdapter(adapter);   
griditem的Layout:
   
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent" android:layout_width="fill_parent"
android:orientation="vertical">
<ImageView android:id="@+id/griditem_pic"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="center_horizontal">
</ImageView>
<TextView android:id="@+id/griditem_title"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="center_horizontal" android:text="test">
</TextView>
</LinearLayout>
   
     在许多时候需要将数据库表中的数据显示在ListView、Gallery等组件中。虽然可以直接使用Adapter对象处理,但工作量很大。为此,Android SDK提供了一个专用于数据绑定的Adapter类:SimpleCursorAdapter。
    SimpleCursorAdapter与SimpleAdapter用法相近。只是将List对象换成了Cursor对象。而且SimpleCursorAdapter类构造方法的第四个参数from表示Cursor对象中的字段,而SimpleAdapter类构造方法的第四个参数from表示Map对象中的key。除此之外,这两个Adapter类在使用方法完全相同。
    下面是SimpleCursorAdapter类构造方法定义。
     public SimpleCursorAdapter(Context context,int layout,Cursor c,String[] from,int[] to);
    下例中通过SimpleCursorAdapter类将数据库表绑定在ListView上,也就是说,该ListView会显示数据表的全部记录。在绑定数据前,需要先编写一个SQLiteOpenHelper类的子类,用于操作数据库,代码如下:
package com.li;
import java.util.Random;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBService extends SQLiteOpenHelper {
private final static int DATABASE_VERSION = 1;
private final static String DATABASE_NAME = "test.db";
public DBService(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
//创建表
String sql = "CREATE TABLE [t_test](" + "[_id]AUTOINC,"
+ "[name]VARCHAR2(20) NOT NULL CONFLICT FAIL,"
+ "CONSTRAINT[sqlite_autoindex_te_test_1]PRIMARY KEY([_id]))";
db.execSQL(sql);
//向test数据库中插入20条记录
Random random = new Random();
for ( int i = 0;i<20;i++)
{
String s = "";
for(int j=0;j<10;j++)
{
char c = (char)(97+random.nextInt(26));
s+=c;
}
db.execSQL("insert into t_test(name)values(?)",new Object[]{s});
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
//执行查询语句
public Cursor query(String sql,String[] args)
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(sql, args);
return cursor;
}
}
 
      本例不需要对test.db进行升级,因此,只有在DBService类中的oncreate()方法中有创建数据库表的代码。DBService类创建了一个test.db数据库文件,并在该文件中创建了t_test表。在该表中包含两个字段_id和name。其中_id是自增字段,并且是主索引。
     下面编写MapsDemo类。MapsDemo类是ListActivity的子类。在该类中的oncreate()方法中创建了DBService对象,然后通过DBService类的query方法查询出t_test表中的所有记录,并返回Cursor对象。MapsDemo类的代码如下:
package com.li;
import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.SimpleCursorAdapter;
public class MapsDemo extends ListActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
DBService dbService = new DBService(this);
//查询数据
Cursor cursor = dbService.query("select * from t_test", null);
//绑定数据
SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter (this,android.R.layout.simple_expandable_list_item_1,cursor,new String[]{"name"},new int[]{android.R.id.text1});
setListAdapter(simpleCursorAdapter);
}
}
 
       SimpleCursorAdapter类构造方法的第四个参数表示返回Cursor对象中的字段名,第五个参数表示要将该字段的值赋给那个组件。该组件在第二个参数中指定的布局文件中定义。
     注意:在绑定数据时,Cursor对象返回的记录集中必须包含一个叫"_id"的字段,否则将无法完成数据绑定。也就是说SQL语句不能是select name from t_contacts.如果在数据表中没有"_id"字段,可以采用其他方法来处理。
     读到这里可能有人要问:数据存到哪里去了?系统在手机内存中的/data/data/<package name>/databases目录中创建数据库文件。










