
[英]changing cursor of CursorAdapter gives staleDataException
[英]StaleDataException:Attempted to access a cursor after it has been closed
在我的应用程序中,我正在使用SimpleCursorAdapter更新Listviews。 此SimpleCursorAdapter从Cursor对象获取数据。 在这里,当我在onCreate方法中关闭游标时,它将引发StaleDataException:在游标关闭后尝试访问它 。 但是当我在游标上删除此close方法时,它没有发生并且运行良好 。但是,如果我们在游标上删除了close方法,那么它不会造成内存泄漏吗?
使用cursor.close()-
//the columns which we want to show in list view
private static final String[] columnsToUse = new String[]{
UserDictionary.Words.WORD,
UserDictionary.Words.FREQUENCY};
// array of item ids where above two entries will be saved
private static final int[] toView = new int[]{
android.R.id.text1,
android.R.id.text2};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//TextView displayTextView = (TextView) findViewById(R.id.display_text);
ListView dictionaryList = (ListView)findViewById(R.id.dictionary_list_view);
ContentResolver resolver = getContentResolver();
Cursor cursor = resolver.query(UserDictionary.Words.CONTENT_URI, null, null, null, null);
cursor.moveToFirst();
SimpleCursorAdapter dictionaryAdapter = new SimpleCursorAdapter(this, android.R.layout.two_line_list_item,
cursor, columnsToUse, toView, 0);
dictionaryList.setAdapter(dictionaryAdapter);
cursor.close();
抛出-StaleDataException:尝试在关闭游标后访问游标
但是,如果我对此cursor.close()进行注释,则不会出现此错误-
//the columns which we want to show in list view
private static final String[] columnsToUse = new String[]{
UserDictionary.Words.WORD,
UserDictionary.Words.FREQUENCY};
// array of item ids where above two entries will be saved
private static final int[] toView = new int[]{
android.R.id.text1,
android.R.id.text2};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//TextView displayTextView = (TextView) findViewById(R.id.display_text);
ListView dictionaryList = (ListView)findViewById(R.id.dictionary_list_view);
ContentResolver resolver = getContentResolver();
Cursor cursor = resolver.query(UserDictionary.Words.CONTENT_URI, null, null, null, null);
cursor.moveToFirst();
SimpleCursorAdapter dictionaryAdapter = new SimpleCursorAdapter(this, android.R.layout.two_line_list_item,
cursor, columnsToUse, toView, 0);
dictionaryList.setAdapter(dictionaryAdapter);
// cursor.close();
这就是Cursor.close()
释放所有资源并使其完全无效的原因 ...如果在适配器之后立即调用Cursor.close()
, CursorAdapter
将使用什么?
为了解决这个问题
在onDestroy()
或当listView
与CursorAdapter
不再需要它时,使用close()
您的Cursor
。
我只想补充一点:
一旦不再关注活动的UI,则应释放绘制UI所需的系统资源。 由于这是在调用onStop()
之后发生的,因此您应该准备好在onStop上释放资源。
因此,使用
onStop()
而不是onDestroy()
方法来关闭游标。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.