我剛剛瞭解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不會幫助 。
所以我可以看到垃圾收集器是不夠的。但我還是不太明白。有人能夠精通這些本地資源嗎?爲什麼垃圾收集還不夠?提前致謝。