从Android用户词典访问数据时光标出错?

时间:2017-06-12 16:23:10

标签: android android-contentprovider android-cursor

公共类MainActivity扩展了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,那么将发生内存泄漏。但编译器没有显示它! 我想知道这里到底发生了什么? 提前致谢! * /

1 个答案:

答案 0 :(得分:0)

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