SQLite在Android中使用注意事项
1、模糊查询的陷阱
这行代码中由于占位符 ? 在单引号内,因此不会被当做占位符,而是对?进行了模糊查找,会产生类似如下报错: android.database.sqlite.SQLiteException: bind or column index out of range: handle 0x3418b0 解决方法: 以上代码可以正确实现从在database中返回的cursor中读取数据,但以下代码会出现问题 2System.out.println(cursor.getString(0)); 会出现类似这个错误:android.database.CursorIndexOutOfBoundsException: Index -1 requested,with a size of 1 3System.out.println(cursor.getString( 关键就是这句cursor.moveToFirst(); 当然使用cursor.getString(0); 方法之后cursor并不会moveToNext 而对于SimpleCursorAdapter而言,则不需先进行cursor.moveToFirst(); 3、SimpleCursorAdapter的 _id 陷阱 使用SimpleCursorAdapter封装Cursor时要求底层数据表的主键列的列名为_id,因为SimpleCursorAdapter只能识别列名为_id的主键 以下代码会报错 java.lang.IllegalArgumentException: column ‘_id’ does not exist
4、关于AutoCompleteTextView 与 SQLite 关联数据源的陷阱 AutoCompleteTextView的使用需要ArrayAdapter 适配器来提供数据源,一般都使用new ArrayAdapter<String> 从字符串的对象数组中得到数据构成ArrayAdapter,对于静态的字符串对象数组来说,这只需初始化时直接写入数据就行,类似这样: 这样便不会引起 “元素数<数组长度” 的问题,然而如果像下面这样: privateString[]test=newString[100]; 这就会引起“元素数<数组长度” 的问题,虽然不会报错,但使用 ArrayAdapter<String> array_ge_ming = new ArrayAdapter<String>(MusicLookup.this,android.R.layout.simple_dropdown_item_1line,test); 来初始化ArrayAdapter,并把ArrayAdapter和AutoCompleteTextView关联后,你会发现,你输入时并不会有自动匹配。 从SQLite得来的数据是动态的,是不能对字符串对象数组进行事先的静态初始化的,为了解决这个问题,我使用了一下方法: privateString[]str_ge_ming_auto;//声明时先不初始化...... (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |