簡單使用SimpleCursorAdapter

若是使用Sqlite,建議和ContentProvider結合使用。這樣數據庫的生命週期就不用本身管了。而後,若是要在好比ListView中顯示,可使用CursorAdapter。簡化的辦法是使用子類SimpleCursorAdapter。android

如下就介紹一下使用sqlite+content provider+cursor adapter的最簡單實現示例。太簡單了,示例如圖:sql

image

首先,要有個Content provider,如不瞭解如何實現,請參考編寫最簡單的Content Provider在Content provider實現中使用SQLiteOpenHelper,下面寫的是結合兩者的:數據庫

public class RiverContentProvider extends ContentProvider {ide

    public static final Uri CONTENT_URI = Uri
            .parse("content://com.easymorse.cp.rivers");svn

    public static final String _ID = "_id";佈局

    public static final String NAME = "name";this

    public static final String LENGTH = "length";google

    private static SQLiteDatabase database;.net

    private static final int DATABASE_VERSION = 2;code

    private static final List<River> RIVERS = new ArrayList<River>();

    static {
        River river = new River("長江", 6380);
        RIVERS.add(river);

        river = new River("黃河", 5464);
        RIVERS.add(river);
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public String getType(Uri uri) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Uri insert(Uri uri, ContentValues contentValues) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public boolean onCreate() {
        database = new RiverDatabaseHelper(getContext(), "rivers", null,
                DATABASE_VERSION).getReadableDatabase();
        return database != null;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder) {
        return database.query("rivers", projection, selection, selectionArgs,
                null, null, sortOrder);
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
            String[] selectionArgs) {
        // TODO Auto-generated method stub
        return 0;
    }

    private static class RiverDatabaseHelper extends SQLiteOpenHelper {

        public RiverDatabaseHelper(Context context, String name,
                CursorFactory factory, int version) {
            super(context, name, factory, version);
        }

        @Override
        public void onCreate(SQLiteDatabase database) {
            database.execSQL("create table if not exists rivers("
                    + " _id integer primary key autoincrement," + " name text,"
                    + "length integer" + ");");

            SQLiteStatement statement = database
                    .compileStatement("insert into rivers(name,length) values(?,?)");

            for (River r : RIVERS) {
                int index = 1;
                statement.bindString(index++, r.getName());
                statement.bindLong(index++, r.getLength());
                statement.executeInsert();
            }

            statement.close();
        }

        @Override
        public void onUpgrade(SQLiteDatabase database, int oldVersion,
                int newVersion) {
            database.execSQL("drop table if exists rivers");
            onCreate(database);
        }

    }

 

這裏寫的很簡略,沒用到的方法都沒實現。

在總的佈局中使用了ListView:

<?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 android:id="@+id/riverList" android:layout_width="fill_parent"
        android:layout_height="fill_parent" />
</LinearLayout>

使用了自定義的ListView佈局,見:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="wrap_content">
    <TextView android:id="@+id/riverName" android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

 

最後是在Activity中使用contentprovider查詢的cursor,生成ListView:

public class ListViewActivity extends Activity {

    private ListView riverListView;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        setRiverListViewAdapter();
    }

    private void setRiverListViewAdapter() {
        riverListView = (ListView) this.findViewById(R.id.riverList);

        Cursor cursor = managedQuery(RiverContentProvider.CONTENT_URI, null,
                null, null, null);
        CursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.row,
                cursor, new String[] { RiverContentProvider.NAME },
                new int[] { R.id.riverName });
        riverListView.setAdapter(adapter);
    }
}

 

源代碼見:

http://easymorse.googlecode.com/svn/tags/CustomListViewDemo-0.1/

相關文章
相關標籤/搜索