光标在Android中从用户字典访问数据时出错



public class MainActivity extensions AppCompatActivity {

    // For the SimpleCursorAdapter to match the UserDictionary columns to layout items.
    private static final String[] COLUMNS_TO_BE_BOUND = new String[]{
            UserDictionary.Words.WORD,
            UserDictionary.Words.FREQUENCY
    };
    private static final int[] LAYOUT_ITEMS_TO_FILL = new int[]{
            android.R.id.text1,
            android.R.id.text2
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Get the TextView which will be populated with the Dictionary ContentProvider data.
        ListView dictListView = (ListView) findViewById(R.id.dictionary_list_view);
        //TextView dictTextView = (TextView) findViewById(R.id.dictionary_text_view);
        Cursor cursor = null;
        try {
            // Get the ContentResolver which will send a message to the ContentProvider.
            ContentResolver resolver = getContentResolver();
            // Get a Cursor containing all of the rows in the Words table.
            cursor = resolver.query(UserDictionary.Words.CONTENT_URI, null, null, null, null);
            SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
                    android.R.layout.two_line_list_item,
                    cursor,
                    COLUMNS_TO_BE_BOUND,
                    LAYOUT_ITEMS_TO_FILL,
                    0
            );
            dictListView.setAdapter(adapter);
        } catch (Exception e) {
            e.getMessage();
        } finally {
            cursor.close();
        }
    }
}

/*如果我不关闭cusor,那么就会发生内存泄漏。但是编译器没有显示!我想知道这里到底发生了什么?提前感谢!*/

当我们打开游标时,它必须关闭,否则系统全局区域会出现内存泄漏。
当程序为数据结构分配内存,然后从不释放该内存并且不重用该内存时,会发生内存泄漏。下次程序需要数据结构时,它会再次分配更多内存。随着时间的推移,可用内存似乎在缩小,这称为"内存泄漏"。通过确保在使用完数据结构时释放为数据结构分配的内存来克服内存泄漏

最新更新