我刚刚了解Android中有关SQLite数据库的游标。我有以下的方法,从一个宠物收容所数据库中检索宠物信息并将其显示在一个简单的TextView:在Android中关闭游标如何防止内存泄漏?
私人无效displayDatabaseInfo(){// 创建和/或打开数据库从中读取 SQLiteDatabase db = mDbHelper.getReadableDatabase();
// Perform query Cursor cursor = db.query(PetEntry.TABLE_NAME, null, null, null, null, null, null); TextView displayView = (TextView) findViewById(R.id.text_view_pet); try { displayView.setText("The pets table contains " + cursor.getCount() + " pets.\n\n"); displayView.append(PetEntry._ID + " - " + PetEntry.COLUMN_PET_NAME + " - " + PetEntry.COLUMN_PET_BREED + " - " + PetEntry.COLUMN_PET_GENDER + " - " + PetEntry.COLUMN_PET_WEIGHT + "\n"); // Figure out the index of each column int idColumnIndex = cursor.getColumnIndex(PetEntry._ID); int nameColumnIndex = cursor.getColumnIndex(PetEntry.COLUMN_PET_NAME); int breedColumnIndex = cursor.getColumnIndex(PetEntry.COLUMN_PET_BREED); int genderColumnIndex = cursor.getColumnIndex(PetEntry.COLUMN_PET_GENDER); int weightColumnIndex = cursor.getColumnIndex(PetEntry.COLUMN_PET_WEIGHT); // Iterate through all the returned rows in the cursor while (cursor.moveToNext()) { // Use that index to extract the String or Int value of the word // at the current row the cursor is on. int currentID = cursor.getInt(idColumnIndex); String currentName = cursor.getString(nameColumnIndex); String currentBreed = cursor.getString(breedColumnIndex); int currentGender = cursor.getInt(genderColumnIndex); int currentWeight = cursor.getInt(weightColumnIndex); // Display the values from each column of the current row in the cursor in the TextView displayView.append("\n" + currentID + " - " + currentName + " - " + currentBreed + " - " + currentGender + " - " + currentWeight); } } finally { cursor.close(); } }
我只是不明白为什么我们要关闭游标。课程说这是为了避免内存泄漏,但游标对象是方法内部的局部变量,并且在方法结束后将是垃圾回收。那么为什么我们仍然需要调用close()?
我一直在做一些研究,并看看这里的其他问题和答案。这一个给出了一个提示:A few questions about SQLite database cursors in Android。它说
或关闭()它自己。不这样做会泄漏内存,因为光标背后有本地资源(例如对数据库的 文件句柄),所以GC不会帮助 。
所以我可以看到垃圾收集器是不够的。但我还是不太明白。有人能够精通这些本地资源吗?为什么垃圾收集还不够?提前致谢。