首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > 移动开发 >

简略使用SimpleCursorAdapter

2013-02-27 
简单使用SimpleCursorAdapter??首先,要有个Content provider,如不了解如何实现,请参考编写最简单的Content

简单使用SimpleCursorAdapter

?

?

首先,要有个Content provider,如不了解如何实现,请参考编写最简单的Content Provider和在Content provider实现中使用SQLiteOpenHelper,下面写的是结合二者的:

?

  • ? ?? ?? ?? ?? ?? ???+ "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:

  • <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布局,见:

  • <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:

    ?SimpleCursorAdapter(安卓巴士源码).rar?

    ?
    ? ?? ? SimpleCursorAdapter类构造方法的第四个参数表示返回Cursor对象中的字段名,第五个参数表示要将该字段的值赋给那个组件。该组件在第二个参数中指定的布局文件中定义。

    ? ???注意:在绑定数据时,Cursor对象返回的记录集中必须包含一个叫"_id"的字段,否则将无法完成数据绑定。也就是说SQL语句不能是select name from t_contacts.如果在数据表中没有"_id"字段,可以采用其他方法来处理。
    ? ???读到这里可能有人要问:数据存到哪里去了?系统在手机内存中的/data/data/<package name>/databases目录中创建数据库文件。