在我的应用程序中,我使用SimpleCursorAdapter来更新Listviews。此SimpleCursorAdapter从Cursor对象获取数据。这里当我在onCreate方法中关闭游标时,它会抛出 StaleDataException:在游标关闭后尝试访问游标。但是当我在游标上移除了这个关闭方法然后它没有发生并且它运行良好。但是如果我们删除游标上的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();
throw - 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();
答案 0 :(得分:2)
如果您在适配器后面Cursor.close()
调用Cursor.close()
使用的CursorAdapter
,那么这是close()
releases all of its resources and making it completely invalid ... 的内容
要解决它,
{p>Cursor
onDestroy()
listView
或CursorAdapter
以及Brent
将不再需要它。
答案 1 :(得分:0)
我想补充一点:
只要活动的UI不再处于焦点,就应释放绘制UI所需的系统资源。由于这是在调用onStop()
之后发生的,因此您应该准备好在onStop上尽快释放资源。
因此,请使用
onStop()
代替onDestroy()
方法关闭游标。