Android开发中常见错误——数据存储

来源:互联网 发布:qt4.8.4 源码下载 编辑:程序博客网 时间:2024/05/18 02:45

1、使用场景:

adapter = new SimpleCursorAdapter(this,R.layout.item_list,cursor                ,new String[]{"id","name","age"},                new int[]{R.id.tv_id,R.id.tv_name,R.id.tv_age}                ,2);报错:    Caused by: java.lang.IllegalArgumentException: column '_id' does not exist at android.database.AbstractCursor.getColumnIndexOrThrow(AbstractCursor.java:302)         at android.support.v4.widget.SimpleCursorAdapter.findColumns(SimpleCursorAdapter.java:317)    at android.support.v4.widget.SimpleCursorAdapter.<init>(SimpleCursorAdapter.java:92)    at com.dong.sqlitedemo.MainActivity.click(MainActivity.java:79)

错误:与cursor有关
分析:在检查上下文,都没发现错误,然后发现在代码中根本没有”_id”的代码,所以应该是cursor自动加的
SimpleCursorAdapter:规定展示数据的时候,主键名必须是以”_”开头:如:”_id”
解决办法:在创建表示,将列属性”id”改为”_id”,再运行,发现问题解决
或者自定义适配器

2、使用场景:

Cursor cursor = db.rawQuery(“select * from person”,null);
db.close();
if(cursor != null && cursor.getCount() > 0){…}

报错:
java.lang.IllegalStateException:
Cannot perform this operation because the connection pool has been closed.

错误:数据库已经关闭,不能再操作
分析:因为cursor中有多组数据,而数据库被关闭的太早,还没操作完,所以报错
解决办法:将数据完全操作完后,再关闭数据库

3、使用场景:

if(cursor != null && cursor.getCount() > 0){        //  cursor.moveToNext(); 改正        int id = cursor.getInt(0);        String name = cursor.getString(1);        int age = cursor.getInt(2);报错:    android.database.CursorIndexOutOfBoundsException:         Index -1 requested, with a size of 1

错误:cursor下标越界异常
分析:cursor游标还没有移动就开始操作,此时的游标并没有数据,长度为0,下标是-1,所以会报越界异常
解决办法:先将游标cursor移动到下一位,再对cursor进行取数据,即cursor.moveToNext()

4、使用场景:读取短信记录

报错:     Caused by: java.lang.SecurityException:     Permission Denial: opening provider com.android.providers.telephony.SmsProvider     from ProcessRecord{539187fc 1027:com.dong.contentresovlerdemo/u0a54}    (pid=1027, uid=10054) requires android.permission.READ_SMS or    android.permission.WRITE_SMS

错误:没有权限,无法读取
分析:在清单文件中,没有加上操作短信数据库的权限
解决办法:在清单文件中加上权限即可:android.permission.READ_SMS or
android.permission.WRITE_SMS

5、使用场景:

String snippet = cursor.getString(cursor.getColumnIndex("snippet"));    long date = cursor.getLong(cursor.getColumnIndex("date"));          Cursor cursor2 = SMSContentResolverHelper.getNumberSMS(getContentResolver(), id);    cursor2.moveToFirst();    //String address = cursor2.getString(cursor.getColumnIndex("address"));    改正:String address = cursor2.getString(cursor2.getColumnIndex("address"));报错:    E/AndroidRuntime(1148):     Caused by: java.lang.IllegalStateException:     Couldn't read row 0, col -1 from CursorWindow.      Make sure the Cursor is initialized correctly before accessing data from it.

错误:不能读取该位置:row 0, col -1 ,要确保查询的字段在cursor中存在
分析:因为操作了两个cursor,所以将cursor搞混了
解决办法:正确操作所要操作的cursor

0 0
原创粉丝点击