2017-06-12 53 views
0

公共類MainActivity擴展AppCompatActivity {從Android的用戶詞典訪問數據時光標出錯?

// 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然後會出現內存泄漏。但編譯器沒有顯示它! 我想知道這裏究竟發生了什麼? 在此先感謝! */

+0

您不必在適配器中關閉遊標,直到完成使用它們 – tyczj

回答

0

當我們打開遊標時,必須關閉遊標,否則系統全局區域會出現內存泄漏。
當程序爲數據結構分配內存然後從不釋放該內存並且不重用該內存時,會發生內存泄漏。下一次該程序需要數據結構時,它會再次分配更多內存。隨着時間的推移,可用內存似乎在縮小,這被稱爲「內存泄漏」。通過確保爲數據結構分配的內存在使用該數據結構時解除分配,可以克服內存泄漏問題