私はAndroidのカーソルをSQLiteデータベースに関して学んでいます。私は、ペットの避難所データベースからペットの情報を取得し、簡単なのTextViewにそれを示し、次の方法があります。)Androidでカーソルを閉じるとメモリリークを防止するにはどうすればよいですか?
ます。private void 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には がありません。これは、カーソルの後ろにネイティブリソースがあるためです(たとえば、 ファイルがデータベースにハンドルされます)。
私はガベージコレクタでは不十分であることがわかります。しかし、私はまだよく理解していません。誰かがこれらのネイティブリソースを黙想することができますか?なぜガベージコレクションでは十分ではありませんか?前もって感謝します。