Finalizing a Cursor that has not been deactivated or closed

Finalizing a Cursor that has not been deactivated or closed

 


先貼出代碼:

 

 

public List<UnitInfo> findAllGroup() {
		List<UnitInfo> infos=new ArrayList<UnitInfo>();
		try {
			db = dbManager.openDatabase();
			String sql="SELECT * FROM dict_unit_display";
			System.out.println("-------db---open------:"+db.isOpen());
			cursor=db.query("dict_unit_display", null, null, null, null, null, null);
			System.out.println("---------------cursor--close---:"+cursor.isClosed());
			while (cursor.moveToNext()) {
				UnitInfo unit=new UnitInfo();
				unit.setId(cursor.getLong(cursor.getColumnIndex("ID")));
				unit.setUnitCode(cursor.getString(cursor.getColumnIndex("UNIT_CODE")));
				unit.setUnitName(cursor.getString(cursor.getColumnIndex("UNIT_NAME")));
				unit.setUnitSimpleName(cursor.getString(cursor.getColumnIndex("UNIT_SIMPLE_NAME")));
				unit.setUnitNode(cursor.getString(cursor.getColumnIndex("UNIT_NODE")));
				unit.setUnitFatherNode(cursor.getString(cursor.getColumnIndex("UNIT_NODE_FATHER")));
				System.out.println("----------------------------------");
				System.out.println("-----ID-----:"+ unit.getId());
				System.out.println("-----UNIT_CODE-----:" + unit.getUnitCode());
				System.out.println("-----UNIT_NAME-----:" + unit.getUnitName());
				System.out.println("-----UNIT_SIMPLE_NAME-----:" + unit.getUnitSimpleName());
				System.out.println("-----UNIT_NODE-----:" + unit.getUnitNode());
				System.out.println("-----UNIT_NODE_FATHER-----:" + unit.getUnitFatherNode());
				System.out.println("----------------------------------");
				infos.add(unit);
			}
		} catch (Exception e) {
			System.out.println("------findAllGroup-----數據讀取錯誤");
		} finally {
			DBManager.closeDatabase(db, cursor);
		}
		return infos;
	}
 

代碼寫的看似沒有任何問題,但是由於Cursor的獨特性,不得不吐糟下,Cursor取值採用的是先取下標再根據下標去取對應的返回值,這裏面就有個問題,如果當前字段在數據庫中爲 空值 那麼通過Cursor  getString()或者getLong()的時候就會出現問題,進而導致一連串的錯誤。


解決方法就是直接用下標去取值就行了。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章